有些時候类早,在 Bean 的初始化中锌唾,需要使用 Spring 框架自身的對象來執(zhí)行一些操作灼伤,比如獲取 ServletContext 的一些參數(shù),獲取 ApplicaitionContext 中的 BeanDefinition 的名字咪鲜,獲取 Bean 在容器中的名字等等狐赡。為了讓 Bean 可以獲取到框架自身的一些對象,Spring 提供了一組以 Aware 為結(jié)尾的接口疟丙。
這些接口均繼承于 org.springframework.beans.factory.Aware
標記接口颖侄,并提供了由 Bean 實現(xiàn)的 set 方法鸟雏,Spring 通過基于 setter 的依賴注入方式,使相應(yīng)的對象可以被 Bean 使用览祖。以下是一些重要的 Aware 接口:
- ApplicationContextAware:獲得 ApplicationContext 對象孝鹊,可以用來獲取所有 Bean definition 的名字;
- BeanFactoryAware:獲得 BeanFactory 對象展蒂,可以用來檢測 Bean 的作用域又活;
- BeanNameAware:獲得 Bean 在配置文件中定義的名字;
- ResourceLoaderAware:獲得 ResourceLoader 對象锰悼,可以獲得 classpath 中的某個文件柳骄;
- ServletContextAware:在 MVC 應(yīng)用中,可以獲取 ServletContext 對象箕般,可以讀取 Context 中的參數(shù)耐薯;
- ServletConfigAware: 在 MVC 應(yīng)用中,可以獲取 ServletConfig 對象丝里,可以讀取 Config 中的參數(shù)曲初。
public class TestService implements ApplicationContextAware,
ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
BeanNameAware, EnvironmentAware, ImportAware, ResourceLoaderAware{
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
System.out.println("執(zhí)行setBeanClassLoader,ClassLoader Name = " + classLoader.getClass().getName());
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("執(zhí)行setBeanFactory,setBeanFactory:: giraffe bean singleton=" + beanFactory.isSingleton("giraffeService"));
}
@Override
public void setBeanName(String s) {
System.out.println("執(zhí)行setBeanName: Bean Name defined in context="+s);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("執(zhí)行setApplicationContext:: Bean Definition Names="
+ Arrays.toString(applicationContext.getBeanDefinitionNames()));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
System.out.println("執(zhí)行setApplicationEventPublisher");
}
@Override
public void setEnvironment(Environment environment) {
System.out.println("執(zhí)行setEnvironment");
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
Resource resource = resourceLoader.getResource("classpath:spring-beans.xml");
System.out.println("執(zhí)行setResourceLoader:: Resource File Name="+ resource.getFilename());
}
@Override
public void setImportMetadata(AnnotationMetadata annotationMetadata) {
System.out.println("執(zhí)行setImportMetadata");
}
}