一、接口介紹
當一個類實現了這個接口(ApplicationContextAware)之后,這個類就可以方便獲得ApplicationContext中的所有bean。換句話說,就是這個類可以直接獲取spring配置文件中,所有引用到的bean對象。
二、接口使用
1.編寫工具類
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工具類
<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(); }