Spring中ApplicationContextAware接口使用理解

1、接口介绍
当一个类实现了这个接口(ApplicationContextAware)以后,这个类就能够方便得到ApplicationContext中的全部bean。换句话说,就是这个类能够直接获取spring配置文件中,全部引用到的bean对象。web

2、接口使用spring

1.编写工具类app

 1 import org.springframework.beans.BeansException;  2 import org.springframework.context.ApplicationContext;  3 import org.springframework.context.ApplicationContextAware;  4 /**
 5  * Created by zl on 2018/7/7.  6  */
 7 public class BeanFactoryUtil implements ApplicationContextAware {  8     protected static ApplicationContext ctx = null;  9  
10  @Override 11     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 12         ctx = applicationContext; 13  } 14  
15     public static Object getBean(String beanId) { 16         return ctx.getBean(beanId); 17  } 18 }

2.在applicationContext.xml中注册BeanFactoryUtil工具类ide

<bean id="beanFactoryUtil" class="com.boss.utils.BeanFactoryUtil"/>

3.测试工具

@Test public void test() { new ClassPathXmlApplicationContext("applicationContext.xml");// 加载applicationContext.xml(模拟启动web服务)
  UserDao userDaoImpl = (UserDao) BeanFactoryUtil.getBean("userDaoImpl"); userDaoImpl.sayHello(); }
相关文章
相关标签/搜索