在servlet中自动装配

Mah*_*leh 35 spring servlets dependency-injection autowired java-ee

我想在servlet中使用spring autowiring,所以这是我的代码:

@Configurable
public class ImageServlet extends HttpServlet {

   @Autowired
   private SystemPropertyDao systemPropertyDao;

   @Override
   public void init() throws ServletException {


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

}
Run Code Online (Sandbox Code Playgroud)

SystemPropertyDao注释时@Repository

和我的applicationContext.xml:

<context:component-scan base-package="com.basepackage" />
<mvc:annotation-driven />
<context:annotation-config />
<context:spring-configured/>
Run Code Online (Sandbox Code Playgroud)

web.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>
Run Code Online (Sandbox Code Playgroud)

有时自动装配工作,有时它不工作(对spring bean systemPropertyDao的引用为null),任何人都可以告诉我,如果我错过了什么?

Mah*_*leh 71

我按照以下链接中的解决方案,它工作正常: 从JBoss中的servlet访问Spring bean

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*fan 27

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

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
Run Code Online (Sandbox Code Playgroud)

在init()方法的第一行.


归档时间:

查看次数:

33795 次

最近记录:

9 年 前