[NullPointerException,同时在Jersey + Spring框架中使用@Autowired时

问题描述 投票:0回答:2

我创建了一个简单的服务来一起试用Jersey和Spring框架。我正在使用核心Spring(不是Spring Boot)。没有Spring,Jersey框架可以正常工作。添加Spring注释后,@ Autowired无法正常工作。

MyResource.java

@Component
@Path("myresource")
public class MyResource {

    @Autowired
    private AdditionService add;

    @GET
    @Path("/sum/{firstNumber}/{secondNumber}")
    @Produces(MediaType.APPLICATION_JSON)
    public Answer getSum(@PathParam("firstNumber") int firstNumber,
                         @PathParam("secondNumber") int secondNumber) {

        return add.performAction(firstNumber,secondNumber);
    }
}

AdditionService.java

@Component
public class AdditionService {

    @Autowired
    Answer ans;

    public Answer performAction (int first, int second) {
        ans.setAnswer(first+second);
        return ans;
    }
}

Answer.java

@Component
public class Answer {
    private int answer = 200;
    public Answer() {}
    public Answer(int answer) {
        this.answer = answer;
    }
    public int getAnswer() {
        return answer;
    }
    public void setAnswer(int answer) {
        this.answer = answer;
    }
}

AppConfig.java

@Configuration
@ComponentScan(basePackageClasses = {Answer.class,AdditionService.class})
public class AppConfig {}

错误

org.apache.catalina.core.NamingContextListener.addResource naming.jmxRegistrationFailed

NullPointer错误

24-Feb-2020 16:54:30.205 SEVERE [http-nio-8080-exec-6] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [Jersey Web Application] in context with path [/RESTAPIJersey_war] threw exception [java.lang.NullPointerException] with root cause
    java.lang.NullPointerException
        at org.example.company.resources.MyResource.getSum(MyResource.java:27)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
java spring dependency-injection jersey autowired
2个回答
0
投票

这些应该被注释为@Service而不是@Component,然后您将通过继承@Component Annotation的一个或多个@Controllers(甚至是@Restcontrollers)访问这些Services,您可以在其中指定一个@RequestMapping(method = RequestMethod.GET,path =“ / users”)在方法类级别


0
投票

您是否可以尝试从AppConfig中删除@ComponentScan批注并在下面使用lije

@SpringBootApplication(scanBasePackages = "com.example")
@EnableAutoConfiguration
public class AppConfig {
}

还要确保您的AppConfig类应该是可发现的(您可以将AppConfig放在com.example中,然后尝试

© www.soinside.com 2019 - 2024. All rights reserved.