【SpringBoot笔记12】实现xxxAware接口

参考:官方文档

1 Aware接口

Aware 的本意是感知。当bean实现了对应的Aware接口,BeanFactory 就会在产生这个bean的时候根据对应的Aware接口,给这个bean注入相应的属性,这样bean就能够获取外界资源的引用了。

1.1 ApplicationContextAware 和 BeanNameAware

1.1.1 ApplicationContextAware接口

当一个bean实现了org.springframework.context.ApplicationContextAware接口,那么这个实力bean就会被注入ApplicationContext对象,下面是这个接口的定义:

public interface ApplicationContextAware {

    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

使用它的一个例子:

@Component
public class BeanA implements ApplicationContextAware {
    
    private ApplicationContext ctx;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
    
    // ...
}

Spring 2.5开始,可以通过@Autowired自动注入ApplicationContext对象:

@Component
public class BeanA {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    // ...
}

1.1.2 BeanNameAware接口

bean 的内部,它是不知道容器给自己取的id是什么。当一个bean实现了org.springframework.beans.factory.BeanNameAware接口,就可以在创建这个bean的时候将id注入进来。下面是该接口的定义:

public interface BeanNameAware {

    void setBeanName(String name) throws BeansException;
}

这些回调是在属性填充完毕之后,在初始化回调之前调用。

1.2 其它的Aware接口

Spring还提供了一些很重要的Aware接口,这些接口的命名规则就是根据需要依赖的属性来命名的:

接口 注入的属性 Explained in…
ApplicationContextAware Declaring ApplicationContext. ApplicationContextAware and BeanNameAware
ApplicationEventPublisherAware Event publisher of the enclosing ApplicationContext. Additional Capabilities of the ApplicationContext
BeanClassLoaderAware Class loader used to load the bean classes. Instantiating Beans
BeanFactoryAware Declaring BeanFactory. ApplicationContextAware and BeanNameAware
BeanNameAware Name of the declaring bean. ApplicationContextAware and BeanNameAware
BootstrapContextAware Resource adapter BootstrapContextthe container runs in. Typically available only in JCA aware ApplicationContextinstances. JCA CCI
LoadTimeWeaverAware Defined weaver for processing class definition at load time. Load-time Weaving with AspectJ in the Spring Framework
MessageSourceAware Configured strategy for resolving messages (with support for parametrization and internationalization). Additional Capabilities of the ApplicationContext
NotificationPublisherAware Spring JMX notification publisher. Notifications
ResourceLoaderAware Configured loader for low-level access to resources. Resources
ServletConfigAware Current ServletConfig the container runs in. Valid only in a web-aware Spring ApplicationContext. Spring MVC
ServletContextAware Current ServletContext the container runs in. Valid only in a web-aware Spring ApplicationContext. Spring MVC

猜你喜欢

转载自blog.csdn.net/hbtj_1216/article/details/86427051
今日推荐