Bean 被初始化但注入抛出 npe

Bean gets initialized but injection throws npe

我正在使用配置文件创建一个 bean。该 bean 在服务器启动期间被初始化,我在其中有一个调试点并被触发。当我的 restApi 调用处理程序方法时,它抛出 NPE,其中 coinResponse 为空。请让我知道我在这里做错了什么。

配置文件

package com.foo.service.handler;
@Configuration
@ComponentScan("com.foo.service")
public class CacheConfiguration {
    @Bean
    public CoinResponse getCoinResponse() {
        return new CoinResponse();
    }
}

处理程序文件

package com.foo.service.handler;
public class DetailsHandler {

    @Inject
    CoinResponse getCoinResponse;
    public List<CoinResponse> getCoinDetails() {
        System.out.println(getCoinResponse.getClass());
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>foosvc</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
    </context-param>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>
            org.glassfish.jersey.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.foo.service</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>

</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <context:annotation-config />

    <context:component-scan base-package="com.fomo.service" />

</beans>

可能 DetailsHandler 没有在 Spring 中定义。

依赖注入 (@Inject) 只能在 Spring 使用的 classes 内部发生。 请尝试在 DetailsHandler class 中创建一个无操作构造函数并在那里放置一个断点。

根据您的 spring 配置,您可能应该使用 @Component 或其构造型之一(例如 @Controller)对其进行注释