当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有引用到的bean对象。

一.基于xml的方式

1.工具类实现ApplicationContextAware接口

public class BeanFactoryUtil implements ApplicationContextAware {
    protected static ApplicationContext ctx = null;


     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         ctx = applicationContext;
     }

     public static Object getBean(String beanId) {
         return ctx.getBean(beanId);
     }
}

 

2.UserDao

public class UserDao {
}

 

3.配置文件中注册

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="beanFactoryUtil" class="com.itheima.testAware.BeanFactoryUtil"/>
    <bean id="userDao" class="com.itheima.testAware.UserDao"/>
</beans>

 

4.测试类

public class AwareTest {
    public static void main(String []args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        //ApplicationContext context=new AnnotationConfigApplicationContext(EventConfig.class);
        UserDao userDao = (UserDao)BeanFactoryUtil.getBean("userDao");
        System.out.println(userDao);

    }
}

 

 


 

一.基于注解的方式

1.工具类实现ApplicationContextAware接口

public class BeanFactoryUtil implements ApplicationContextAware {
    protected static ApplicationContext ctx = null;


     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         ctx = applicationContext;
     }

     public static Object getBean(String beanId) {
         return ctx.getBean(beanId);
     }
}

 

2.UserDao

public class UserDao {
}

 

3.配置类

@Configuration
@ComponentScan("com.itheima.testAware")
public class AwareConfig {

}

 

4.测试类

public class AwareTest {
    public static void main(String []args) {
      //  ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext context=new AnnotationConfigApplicationContext(AwareConfig.class);
        UserDao userDao = (UserDao)BeanFactoryUtil.getBean("userDao");
        System.out.println(userDao);

    }
}

 

posted on 2020-09-15 00:33  从精通到陌生  阅读(871)  评论(0编辑  收藏  举报