2010-11-15 74 views
5

我在我的应用程序中使用Spring框架(2.5.4),加载时编织和一切工作正常无处不在(在Spring的bean中,在非Spring实体中),除非我尝试自动装入字段注释为@Configurable一个servlet,然后我得到一个不错的NullPointerException异常...Spring @Autowired在Servlet中


@Configurable(dependencyCheck=true) 
public class CaptchaServlet extends HttpServlet{ 
    @Autowired 
    private CaptchaServiceIface captchaService; 

    @Override 
    public void init(ServletConfig config) throws ServletException { 
     super.init(config); 
    // ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()); 
    // captchaService = (CaptchaServiceIface) ctx.getBean("captchaService"); 
    } 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     Captcha c = captchaService.getCatpcha(); 
     req.getSession().setAttribute("captchaAnswer", c.getAnswer()); 
     resp.setContentType("image/png"); 
     ImageIO.write(c.getImage(), "png", resp.getOutputStream()); 
    } 
} 

<context:load-time-weaver/> 
<context:spring-configured/> 
<context:component-scan base-package="cz.flexibla2" /> 

约我在做什么错误有什么建议?

谢谢。

+1

我不确定,但可能是因为servlet类被servlet容器加载而不是spring容器。 – 2010-11-15 12:27:34

+2

@ abhin4v:加载时织入的思想是允许任何东西加载类,而不仅仅是Spring。 – skaffman 2010-11-15 12:29:11

+0

@malejpavouk,这种行为的最终解决方案是什么,请分享一下吗? – 2012-08-07 10:19:20

回答

3

另请参阅mailing list discussion和bug报告https:// bugs.eclipse.org/bugs/show_bug.cgi?id=317874。我同意,直观地说,servlet上的@Configurable注释应该足以向Spring框架指示在使用<context:spring-configured/>时,实例化的servlet将在春季进行配置。我还观察到,使用-javaagent:/path/to/aspectjweaver.jar而不是spring-instrument * .jar或spring-agent.jar时,可以实现所需的行为。请通过https:// jira.springframework.org/browse/SPR向Spring Jira提出问题。我相信问题可能是servlet类(不是servlet的实例,而是类本身)在调用Spring ContextLoaderListener之前加载,因此Spring框架在调用Servlet类之前没有机会使用它加载。

加载时织入的spring工具似乎基于能够在加载类之前转换类字节码。如果servlet容器持有Spring类转换之前获得的Class对象的实例,那么它(servlet容器)将无法生成已转换的类的实例,也不能生成实例实例使用该Class对象上的工厂方法创建。

+0

https://jira.springsource.org/browse/SPR-7801 – malejpavouk 2010-12-08 17:04:09

6

这很可能是因为Servlet容器正在被servlet容器实例化并初始化,之前 Spring上下文被初始化,并且它是处理加载时编织的Spring上下文。

是你的<context:load-time-weaver/>东西在servlet里面处理Spring上下文还是在webapp级别?前者几乎肯定不会工作(出于上述原因),但webapp级别的配置可能会起作用(使用ContextLoaderListener)。

+0

我正在web.xml中使用contextLoaderLister ...并且似乎有一些成功注入的bean是在servlet之前创建的... – malejpavouk 2010-11-16 10:07:11

+0

上下文:load-time-weaver标记本身位于spring配置文件中。 。不知道它是否重要,但我使用spring-agent来测试我的代码 – malejpavouk 2010-11-16 10:16:24