Spring源码窥探之:xxxAware接口

Aware接口是一个标志性接口,继承此接口的接口xxxAware的实现类,在容器创建完成后,会回调实现方法,下面举例:

1. 有很多xxxAware接口,下面举两个例子

/**
 * description: 将实现xxxAware接口的Bean注册到IOC容器中的时候,会将xxxAware的实现方法进行回调操作
 *
 * @author 70KG
 * @date 2018/12/17
 */
@Component
public class MyAware implements ApplicationContextAware, BeanNameAware {

    private ApplicationContext applicationContext;

    private String beanName;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        Cat cat = (Cat) applicationContext.getBean("cat");
        System.out.println("------->" + cat);
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
        System.out.println("------->" + beanName);
    }
}

2. 配置类

/**
 * description
 *
 * @author 70KG
 * @date 2018/12/17
 */
@Configuration
public class MyConfig {

    @Bean
    public Cat cat() {
        return new Cat();
    }

    @Bean
    public Dog dog() {
        return new Dog();
    }

    @Bean
    public MyAware myAware() {
        return new MyAware();
    }

}

3. 测试类

/**
 * description
 *
 * @author 70KG
 * @date 2018/12/17
 */
public class Test01 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
        Cat cat = (Cat) app.getBean("cat");
        System.out.println("------->" + cat);
    }
}

4. 结果

------->myAware
------->com.nmys.story.springCore.springioc.importBean.Cat@78b66d36
------->com.nmys.story.springCore.springioc.importBean.Cat@78b66d36
原文地址:https://www.cnblogs.com/zhangjianbing/p/10130250.html