Spring之Aware

Spring之Aware

Spring 中的Aware用于帮助bean获取Spring Bean获取Spring容器的功能。

如这些Aware:

 ApplicationContextAware//获取容器服务
BeanNameAware//获取BeanName
ResourceLoaderAware//获取资源加载器服务

 

想获取什么功能就实现什么Aware即可。

ApplicationContextAware为例,实现获取Aware功能的步骤:

1、实现相应的Aware接口

2、重写setXXX方法

此时以及可以获取到ApplicationContext的功能了,不过还需要将这个Bean加入容器中。

3、加入容器

直接使用注解即可。

@Service
public class AppContextAware implements ApplicationContextAware {
   ApplicationContext applicationContext;


   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
       this.applicationContext=applicationContext;
  }
   
    public void hello(){
       //user为容器中存在的bean
       User user = applicationContext.getBean("user", User.class);
       System.out.println(user);
       
       //获取容器的环境、User.name为设置好的属性
       Environment environment = applicationContext.getEnvironment();
       String property = environment.getProperty("User.name");
       System.out.println(" 属性:"+property);

    }
}

 

 

因为实现的是ApplicationContextAware接口,所以能获取到容器的所有功能。

为避免混乱,通常是用什么功能获取那个Aware.

posted @ 2020-01-05 20:04  cgl_dong  阅读(282)  评论(0编辑  收藏  举报