使用@Autowired属性时的NPE(但不是在使用ApplicationContext设置属性时)

时间:2015-10-18 19:55:01

标签: java spring-mvc autowired

我正在尝试使用@Autowired注释在jax-rs restful服务上设置属性,但是在引用该属性时我得到一个空指针异常。这是我第一次尝试使用此注释。

package com.pallelli.mvcpract.rest;

import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.pallelli.hibpract.policymodel.PolicyDao;
import com.pallelli.hibpract.policymodel.beans.Risk;

@Service("riskService")
@Path("risk")
@Component
public class RiskService {

    //@Context
    //private ServletContext context; 

    @Autowired
    private PolicyDao policyDao;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response storeRisk(Risk risk) {

        //ApplicationContext ctx = 
        //WebApplicationContextUtils.getWebApplicationContext(context);
        //policyDao = ctx.getBean(PolicyDao.class);

        policyDao.addRisk(risk);
        risk.setName(risk.getName()+" : processed");
        return Response.ok(risk).status(200).build();
    }
}

如果我删除了注释以便使用应用程序上下文创建policyDao,那么一切都有效,因此我认为spring正在了解bean。

我在mvc-dispatcher-servlet.xml中使用以下内容来获取spring来查找bean。

<context:component-scan base-package="com.pallelli.mvcpract.rest" />
<context:component-scan base-package="com.pallelli.hibpract.policymodel" />

这是PolicyDao类(我知道它是'错误')

package com.pallelli.hibpract.policymodel;

import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.pallelli.hibpract.policymodel.beans.Risk;

@Component
public class PolicyDao {
    public void addRisk(Risk risk) {
        Session session = null;
        try {
            session = Main.getSessionFactory().openSession();
            session.beginTransaction();
            session.persist(risk);
            session.getTransaction().commit();
        }
        finally {
            if(session != null) session.close();
        }
    }
}

调试日志似乎表明自动装配工作

20:10:41 DEBUG DefaultListableBeanFactory:220 - Creating shared instance of singleton bean 'riskService'
20:10:41 DEBUG DefaultListableBeanFactory:449 - Creating instance of bean 'riskService'
20:10:41 DEBUG InjectionMetadata:71 - Registered injected element on class [com.pallelli.mvcpract.rest.RiskService]: AutowiredFieldElement for private com.pallelli.hibpract.policymodel.PolicyDao com.pallelli.mvcpract.rest.RiskService.policyDao
20:10:41 DEBUG DefaultListableBeanFactory:523 - Eagerly caching bean 'riskService' to allow for resolving potential circular references
20:10:41 DEBUG InjectionMetadata:85 - Processing injected method of bean 'riskService': AutowiredFieldElement for private com.pallelli.hibpract.policymodel.PolicyDao com.pallelli.mvcpract.rest.RiskService.policyDao
20:10:41 DEBUG DefaultListableBeanFactory:220 - Creating shared instance of singleton bean 'policyDao'
20:10:41 DEBUG DefaultListableBeanFactory:449 - Creating instance of bean 'policyDao'
20:10:41 DEBUG DefaultListableBeanFactory:523 - Eagerly caching bean 'policyDao' to allow for resolving potential circular references
20:10:41 DEBUG DefaultListableBeanFactory:477 - Finished creating instance of bean 'policyDao'
20:10:41 DEBUG AutowiredAnnotationBeanPostProcessor:427 - Autowiring by type from bean name 'riskService' to bean named 'policyDao'
20:10:41 DEBUG DefaultListableBeanFactory:477 - Finished creating instance of bean 'riskService'
...
20:18:45 DEBUG DefaultListableBeanFactory:247 - Returning cached instance of singleton bean 'policyDao'

有关为什么RiskService上的自动装配属性为空的任何想法?

1 个答案:

答案 0 :(得分:0)

似乎jax-rs无法处理Spring注释。

需要一些额外的设置才能让jax-rs对象知道Spring Beans。如果没有正确的初始化,则不会处理Autowired,Transactional或任何其他Spring注释。

假设你正在使用Jersey和Spring 3,你需要包含一个在Jersey和Spring之间提供“桥梁”的库:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-spring3</artifactId>
    <version>2.22.1</version>
</dependency>

有一个单独的库为Spring 4提供支持。有关详细信息,请参阅Jersey documentation和此example

您设法获取ApplicationContext,因为它作为属性存储在ServletContext中,因此可以使用静态方法调用从应用程序中的任何位置检索它。正如您所注意到的bean已正确初始化但两个框架之间并没有相互通信。