首页 > 编程语言 > 详细

十三、【接口】Spring接口xxxAware

时间:2020-09-24 22:02:29      阅读:54      评论:0      收藏:0      [点我收藏+]

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

  1. 有很多xxxAware接口,下面举两个例子
/**
 * description: 将实现xxxAware接口的Bean注册到IOC容器中的时候,会将xxxAware的实现方法进行回调操作
 * @author zhangjianbing
 * @date 2020年9月23日
 */
@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);
    }
}
  1. 配置类
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
@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();
    }

}
  1. 测试类
/**
 * @author zhangjianbing
 * @date 2020年9月23日
 */
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);
    }
}
  1. 结果
------->myAware
------->com.nmys.story.springCore.springioc.importBean.Cat@78b66d36
------->com.nmys.story.springCore.springioc.importBean.Cat@78b66d36

十三、【接口】Spring接口xxxAware

原文:https://www.cnblogs.com/zhangjianbing/p/13726710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!