Oli*_*ohm 60
有一种更复杂的方法可以做到这一点.有SpringBeanAutowiringSupport内部的org.springframework.web.context.support,它允许你建立这样的事情:
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)
这将导致Spring查找ApplicationContext绑定到那个ServletContext(例如创建的via ContextLoaderListener)并注入可用的Spring bean ApplicationContext.
Chi*_*ang 31
您的servlet可以使用WebApplicationContextUtils来获取应用程序上下文,但是您的servlet代码将直接依赖于Spring Framework.
另一个解决方案是配置应用程序上下文以将Spring bean作为属性导出到servlet上下文:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="jobbie" value-ref="springifiedJobbie"/>
</map>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
您的servlet可以使用从servlet上下文中检索bean
SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
Run Code Online (Sandbox Code Playgroud)
我找到了一种方法:
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");
Run Code Online (Sandbox Code Playgroud)