37

我想在 servlet 中使用 spring 自动装配,所以这是我的代码:

@Configurable
public class ImageServlet extends HttpServlet {

   @Autowired
   private SystemPropertyDao systemPropertyDao;

   @Override
   public void init() throws ServletException {


   String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER);

}

虽然SystemPropertyDao注释为@Repository

和我的applicationContext.xml

<context:component-scan base-package="com.basepackage" />
<mvc:annotation-driven />
<context:annotation-config />
<context:spring-configured/>

网页.xml

  <servlet>
    <servlet-name>imageServlet</servlet-name>
    <servlet-class>com.xeno.basepackage.ImageServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>imageServlet</servlet-name>
    <url-pattern>/myimages/*</url-pattern>
  </servlet-mapping>

有时自动装配有效,有时则无效(对 spring bean systemPropertyDao 的引用为空),谁能告诉我是否遗漏了什么?

4

2 回答 2

77

我遵循以下链接中的解决方案,它工作正常: Access Spring beans from a servlet in JBoss

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}
于 2012-08-07T11:17:53.127 回答
28

从您的 servlet中删除@Configurable注释并添加:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);

在您的 init() 方法的第一行。

于 2012-08-07T11:14:40.107 回答