Aware接口
Aware接口从字面上翻译过来是感知捕获的含义。(Aware是”意识到的,察觉到的“意思,可得结论实现了Aware系列接口表明可以意识到,可以察觉到)
单纯的bean(指没有实现Aware接口的bean对象)是没有”知觉“的,实现了Aware系列接口的bean可以访问Spring容器,这些Aware系列接口增强了Spring bean的功能,但是也会造成对Spring框架的绑定,增大了与Spring框架的耦合度。
接口源码如下:
// 该接口没有定义任何方法,只是一个标识接口
public interface Aware {
}
Aware的常用子接口有如下:
org.springframework.context.ApplicationContextAware
实现该接口的类可以获取spring容器上下文信息 ApplicationContext。
org.springframework.beans.factory.BeanFactoryAware
根据bean名称获取相应的bean对象。
org.springframework.beans.factory.BeanClassLoaderAware
获取Spring容器的类加载器ClassLoader对象。
org.springframework.beans.factory.BeanNameAware
这个接口的含义就是让实现类知道自己在spring容器中定义的beanName是什么,实际一般开发没啥用。
org.springframework.context.EnvironmentAware
实现这个接口的类能够获取Environment对象,进而可以获取各种系统变量信息,也可以设置变量的有限级别等等;通过Environment对象可以获取Spring boot框架中的application.properties中定义的变量值。
org.springframework.context.ResourceLoaderAware
获取资源加载器ResourceLoader对象,可以获得外部资源文件。
org.springframework.context.annotation.ImportAware
Aware系列接口中的部分常用接口:
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
public interface BeanClassLoaderAware extends Aware {
void setBeanClassLoader(ClassLoader classLoader);
}
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
可以发现Aware系列接口的共性:
- 都是以Aware单词进行结尾
- 都是Aware接口的子接口,即都实现了Aware接口
- 接口内均定义了一个set方法,而方法中的参数是该系列接口名称Aware单词前面的内容,也就是当前bean需要感知的内容,所以我们需要在bean中声明相关的成员变量来接收
举例说明:
@Component
public class ApplicationContextStaticProvider implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return context;
}
// 通过beanName获取Bean
public static Object getBean(String beanName) {
return getApplicationContext().getBean(beanName);
}
// 通过class获取bean
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
// 通过name,以及Clazz返回指定的bean
public static <T> T getBean(String beanName, Class<T> clazz) {
return getApplicationContext().getBean(beanName, clazz);
}
}
@Service
public class DemoBean {
public void test(String str){
System.out.println(str);
}
}
public class AnnotationConfigApplicationContextTests {
@Test
public void scanAndRefreshTestAware() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("org.springframework.context.annotation7");
context.refresh();
DemoBean demoBean= (DemoBean) ApplicationContextStaticProvider.getBean("demoBean");
demoBean.test("test applicationContextAware");
}
}
来源: