Spring注入到Servlet中 [英] Spring injection Into Servlet
问题描述
所以我看到了这个问题:
So I have seen this question:
并且想知道我的方法是否可行.
and was wondering if my method will work out.
1) 在我的 Spring 应用程序上下文中声明 bean
1) Declare beans in my Spring application context
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="validationQuery" value="${jdbc.validationQuery}" />
<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
</bean>
<bean id="apiData" class="com.mydomain.api.data.ApiData">
<property name="dataSource" ref="dataSource" />
<property name="apiLogger" ref="apiLogger" />
</bean>
<bean id="apiLogging" class="com.mydomain.api.data.ApiLogger">
<property name="dataSource" ref="dataSource" />
</bean>
2) 覆盖我的 servlet 的 init 方法,如下所示:
2) Override my servlet's init method as shown:
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
this.apiData = (ApiData)ac.getBean("apiData");
this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
}
在 Web 应用程序部署的这一点上,这会起作用还是 Spring 尚未准备好将 bean 交付给我的 servlet?我是否必须做一些更传统的事情,比如将 bean 放入 web.xml
中?
Will this work or is Spring not yet ready to deliver beans to my servlet at this point in the web applications deployment? Do I have to do something more traditional like putting the beans in web.xml
?
推荐答案
你正在尝试做的事情将使每个 Servlet
有自己的 ApplicationContext
实例.也许这就是你想要的,但我对此表示怀疑.ApplicationContext
对应用程序来说应该是唯一的.
What you are trying to do will make every Servlet
have its own ApplicationContext
instance. Maybe this is what you want, but I doubt it. An ApplicationContext
should be unique to an application.
执行此操作的适当方法是在 ServletContextListener
.
The appropriate way to do this is to setup your ApplicationContext
in a ServletContextListener
.
public class SpringApplicationContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
sce.getServletContext().setAttribute("applicationContext", ac);
}
... // contextDestroyed
}
现在您的所有 servlet 都可以通过 ServletContext
属性访问相同的 ApplicationContext
.
Now all your servlets have access to the same ApplicationContext
through the ServletContext
attributes.
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute("applicationContext");
this.apiData = (ApiData)ac.getBean("apiData");
this.apiLogger = (ApiLogger)ac.getBean("apiLogger");
}
这篇关于Spring注入到Servlet中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!