手动获取spring的ApplicationContext和bean对象改进

通过ApplicationContext的getBean方法来获取Spring容器中已初始化的bean。
FileSystemXmlApplicationContext能够读取classpath下的相对路径
代码如下:

ApplicationContext context = new FileSystemXmlApplicationContext("(你applicationContext.xml在文件夹下的路径)");

遇到一条new指令时,首先将去检查这个指令的参数是否能在常量池中定位到一个类的符号引用,并且检查这个符号引用代表的类是否已经被加载、解析和初始化过。如果没有则进行相应的类加载过程。
如果每一条Action中都new一个ApplicationContext对象 会浪费太多内存
所以可以写一个工具类实现ApplicationContextAware接口,并添加到spring容器中

package org.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware {
 private static ApplicationContext applicationContext;
 public void setApplicationContext(ApplicationContext applicationContext)
 throws BeansException {
 // TODO Auto-generated method stub
 SpringContextUtil.applicationContext = applicationContext;
 }
 public static ApplicationContext getApplicationContext() {
 return applicationContext;
 }
 @SuppressWarnings("unchecked")
 public static <T> T getBean(String name) throws BeansException {
 return (T) applicationContext.getBean(name);
 }
}

并在spring容器中添加

<bean id="springContextHelper" class="org.util.SpringContextUtil"></bean>
//spring中的DAO
<bean id="stuDAOImp" class="org.DAO.Imp.StuDAOImp">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>

在Action中可直接调用SpringContextUtil中getBean方法

StuDAO stuDAOImp = (StuDAO) SpringContextUtil.getBean("stuDAOImp");

注意!getBean()中参数必须与spring容器中bean的id一致

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部