我想在JBoss中编写一个简单的servlet,它将调用Spring bean上的方法。其目的是允许用户通过点击URL来启动内部作业。从JBoss中的servlet访问Spring beans
在servlet中获取Spring bean引用的最简单方法是什么?
JBoss Web服务允许您使用@Resource注释将WebServiceContext注入服务类。在纯servlet中有什么可比的吗?解决这个特定问题的网络服务将使用大锤压碎坚果。
我想在JBoss中编写一个简单的servlet,它将调用Spring bean上的方法。其目的是允许用户通过点击URL来启动内部作业。从JBoss中的servlet访问Spring beans
在servlet中获取Spring bean引用的最简单方法是什么?
JBoss Web服务允许您使用@Resource注释将WebServiceContext注入服务类。在纯servlet中有什么可比的吗?解决这个特定问题的网络服务将使用大锤压碎坚果。
servlet可以使用WebApplicationContextUtils获得应用程序上下文,但随后你的servlet代码对Spring框架的直接依赖。
另一种解决方案是配置应用程序上下文中的Spring bean作为属性导出到servlet上下文:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="jobbie" value-ref="springifiedJobbie"/>
</map>
</property>
</bean>
servlet可以使用
SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
我发现做这件事:
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");
有检索servlet上下文豆是一个更加复杂的方法来做到这一点。有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());
}
}
这将导致春天来查找ApplicationContext
绑到ServletContext
(例如,通过ContextLoaderListener
创建),并注入该ApplicationContext
可用的Spring bean。
不错,谢谢。 – 2009-01-22 01:44:13
这样做并且不使用WebApplicationContextUtils有什么好处?无论哪种方式,它都与Spring有关。 – Elliot 2009-12-29 19:51:20