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

有时候写个小应用,不想搞那么复杂,但又想揩点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的使用权了.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值