Aware,是感应和感知的意思。当bean实现了对应的Aware接口时,BeanFactory会在生产bean时根据它所实现的Aware接口,给bean注入对应的属性,从而让bean获取外界的信息。

aware的层次结构如下

spring aware

简单分析下各个接口的使用

org.springframework.context.ApplicationContextAware接口

实现该接口的类将会获取ApplicationContext的引用。

public interface ApplicationContextAware {

    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

自Spring2.5起,可使用自动装配模式获取ApplicationContext引用:

@RestController
public class AutowiredDemo {
    @Autowired
    ApplicationContext applicationContext;

    @RequestMapping("/helloworld")
    public String demo() {
        System.out.println("通过applicationContext获取的bean实例:"
                + applicationContext.getBean("demoService1"));
        return "demo!";
    }
}

org.springframework.beans.factory.BeanNameAware接口

在bean内部,它并不知道容器给自己取了个什么id,如果想要获取自己在容器中的id,可以实现BeanNameAware接口获取。其setBeanName(string name)方法的参数就是容器为该bean注入的它本身的id。

public interface BeanNameAware {

    void setBeanName(String name) throws BeansException;
}

其他awate接口说明如下

name 说明
ApplicationContextAware 获取ApplicationContext
ApplicationEventPublisherAware 获取ApplicationContext发布的事件
BeanClassLoaderAware 获取加载bean的class loader
BeanFactoryAware 获取BeanFactory
BeanNameAware 获取bean的name
BootstrapContextAware 获取BootstrapContext 
LoadTimeWeaverAware 定义了用于在加载时处理类定义的weaver
MessageSourceAware 消息解析的策略
NotificationPublisherAware jmx事件发布
PortletConfigAware 获取PortletConfig 
PortletConfigAware 当前的PortletContext 
ResourceLoaderAware  
ServletConfigAware 当前容器的ServletConfig 
ServletContextAware 当前容器 的ServletContext 

 

相关文章:

  • 2021-09-28
  • 2021-12-16
  • 2021-08-18
  • 2021-08-06
  • 2021-04-11
  • 2021-05-01
  • 2022-02-17
猜你喜欢
  • 2021-08-04
  • 2022-01-05
  • 2021-05-31
  • 2021-10-15
  • 2021-08-24
  • 2021-08-12
  • 2021-04-19
相关资源
相似解决方案