【问题标题】:Autowiring in servletservlet 中的自动装配
【发布时间】:2012-08-04 08:00:27
【问题描述】:

我想在 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/>

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>

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

【问题讨论】:

  • “自动装配不起作用”是什么意思?例如,它在特定方法中不起作用?
  • @Boris Treukhov(对spring bean systemPropertyDao的引用为空)
  • 请原谅我的无知(有点像已删除的答案),但您使用注入的实际机制是什么?你在任何地方都调用 SpringBeanAutowiringSupport.processInjectionBasedOnServletContext() 吗?
  • 如果你在 web.xml 中配置了 servlet,它的实例可能不止一个。
  • @Msaleh 从 servlet 类 (stackoverflow.com/questions/467235/…) 访问 Spring bean 的方法并不多,所以您选择哪种方式很有趣。在最简单的情况下,您可能会在调用 SpringBeanAutowiringSupport.processInjectionBasedOnServletContext 之前尝试访问 bean,因此它为空。

标签: spring jakarta-ee servlets dependency-injection autowired


【解决方案1】:

我按照以下链接中的解决方案进行操作,效果很好: 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());
  }
}

【讨论】:

  • 非常感谢。一开始我用Resource注解,不起作用,Autowired效果很好。
  • 非常感谢,但是为什么他们在jBoss中特别提到了?它不会在 weblogic 中工作吗??
  • 它可以在 Weblogic 甚至 Tomcat 中工作!这只是文档的标题:解决方案实际上是依赖于标准的 servlet api 和纯 Spring 类。
【解决方案2】:

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

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);

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

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2014-07-26
    • 2012-01-19
    • 2012-02-14
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多