【发布时间】: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