NullPointerException при использовании @Autowired с фреймворками Jersey + Spring - PullRequest
0 голосов
/ 25 февраля 2020

Я создал простой сервис для совместной работы над Джерси и Spring. Я использую ядро ​​Spring (не Spring Boot). Джерси каркас отлично работает без весны. После добавления аннотаций 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;
    }
}

Ответ. 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

Ошибка нулевого указателя

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)

Ответы [ 2 ]

0 голосов
/ 25 февраля 2020

Можете ли вы попробовать удалить аннотацию @ComponentScan из AppConfig и использовать lije ниже

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

Также убедитесь, что ваш класс AppConfig должен быть доступен для обнаружения (вы можете поместить AppConfig в com.example) и попробовать

0 голосов
/ 25 февраля 2020

Они должны быть аннотированы как @Service, а не как @Component, к которому вы затем обращаетесь к этим Сервисам из одного или нескольких @Controllers (mb даже @Restcontrollers), которые наследуют аннотацию @Component, где вы можете указать @RequestMapping (method = RequestMethod.GET, path = "/ users") для методов Classlevel

...