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(); }
相關文章
相關標籤/搜索