【SpringBoot_ANNOTATIONS】自动装配 04 Aware 注入Spring底层组件 & 原理

自动装配 04 Aware 注入Spring底层组件 & 原理

总接口:Aware

  1. 自定义组件想要使用Spring容器底层的一些组件(ApplicationContext BeanFactory 等等)
  2. 需要让自定义组件实现xxAware接口:在创建对象的时候会调用接口规定的方法注入相关组件 总体参照 Aware 接口 ,把Spring底层一些组件注入到自定义的bean中
  3. xxxAware功能:使用xxProcessor 如ApplicationContextAware ==》 ApplicationContextAwareProcessor,利用后置处理器判断实现了哪个接口,就将Bean转成相应的接口类型,再选择注入相应类型的applicationContext
/**
 * 生命周期 感知接口测试
 */
@Component//注入后自动调用实现的感知接口方法
public class Red implements ApplicationContextAware, BeanNameAware, EmbeddedValueResolverAware {
    private ApplicationContext applicationContext;
    @Override
    public void setBeanName(String name) {
        System.out.println("调用了 setBeanName");
        System.out.println("当前bean的名字 " + name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        System.out.println("调用了 setApplicationContext");
    }

    /**
     * 解析占位符
     * @param resolver
     */
    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        System.out.println("调用了 setEmbeddedValueResolver");
        String resolveString = resolver.resolveStringValue(" hello ${os.name} ; age #{22-1}");
        System.out.println("解析的字符串 " + resolveString);
    }
}

配置类

@Configuration
@ComponentScan(value = {"com.example.annotations.service","com.example.annotations.dao","com.example.annotations.controller","com.example.annotations.bean"})
public class MainConfig4Autowire {

}

测试

    @Test
    void autowiredTest(){
        //配置类测试
        System.out.println("准备创建容器");
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig4Autowire.class);
        System.out.println("容器创建完毕");
        
        //关闭容器
        applicationContext.close();
        System.out.println("容器已关闭");
    }

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值