ITeye博客

在Servlet直接获取Spring框架中的Bean

superloafer · 2008-10-21 14:58 · Spring · Markdown

有时候写个小应用,不想搞那么复杂,但又想揩点Spring的油,可以省去一些麻烦。在Application环境下,直接new一个ApplicationContext的实现类,把配置文件传进去然后那些Bean们就可以任凭处置了。同时,在WebApplication环境下,也可以在Servlet中直接获取Spring配置文件的Bean,有两种方法:

  1. 在获取要使用的bean之前拿到当前ServletContext的 ApplicationContext,之后你想要什么尽管get便是了:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object myDao = context.getBean("daoBeanName");

2.


<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
		<property name="attributes">
			<map>
				<entry key="bean1">
					<ref bean="existingBean1"/>
				</entry>
				<entry key="bean2">
					<ref bean="existingBean2"/>
				</entry>
			</map>
		</property>
	</bean>

然后在Servlet里面就可以通过获取属性的方式getServletContext().getAttribute("bean1")来获得Beans的使用权了.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。