美文网首页3springboot
Spring Aware 接口

Spring Aware 接口

作者: happyJared | 来源:发表于2019-10-02 09:44 被阅读0次

    有些时候,在 Bean 的初始化中,需要使用 Spring 框架自身的对象来执行一些操作,比如获取 ServletContext 的一些参数,获取 ApplicaitionContext 中的 BeanDefinition 的名字,获取 Bean 在容器中的名字等等。为了让 Bean 可以获取到框架自身的一些对象,Spring 提供了一组以 Aware 为结尾的接口。

    这些接口均继承于 org.springframework.beans.factory.Aware 标记接口,并提供了由 Bean 实现的 set 方法,Spring 通过基于 setter 的依赖注入方式,使相应的对象可以被 Bean 使用。以下是一些重要的 Aware 接口:

    • ApplicationContextAware:获得 ApplicationContext 对象,可以用来获取所有 Bean definition 的名字;
    • BeanFactoryAware:获得 BeanFactory 对象,可以用来检测 Bean 的作用域;
    • BeanNameAware:获得 Bean 在配置文件中定义的名字;
    • ResourceLoaderAware:获得 ResourceLoader 对象,可以获得 classpath 中的某个文件;
    • ServletContextAware:在 MVC 应用中,可以获取 ServletContext 对象,可以读取 Context 中的参数;
    • ServletConfigAware: 在 MVC 应用中,可以获取 ServletConfig 对象,可以读取 Config 中的参数。
    public class TestService implements   ApplicationContextAware,
            ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
            BeanNameAware, EnvironmentAware, ImportAware, ResourceLoaderAware{
        
        @Override
        public void setBeanClassLoader(ClassLoader classLoader) {
            System.out.println("执行setBeanClassLoader,ClassLoader Name = " + classLoader.getClass().getName());
        }
        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            System.out.println("执行setBeanFactory,setBeanFactory:: giraffe bean singleton=" +  beanFactory.isSingleton("giraffeService"));
        }
        @Override
        public void setBeanName(String s) {
            System.out.println("执行setBeanName: Bean Name defined in context="+s);
        }
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            System.out.println("执行setApplicationContext:: Bean Definition Names="
                    + Arrays.toString(applicationContext.getBeanDefinitionNames()));
        }
        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
            System.out.println("执行setApplicationEventPublisher");
        }
        @Override
        public void setEnvironment(Environment environment) {
            System.out.println("执行setEnvironment");
        }
        @Override
        public void setResourceLoader(ResourceLoader resourceLoader) {
            Resource resource = resourceLoader.getResource("classpath:spring-beans.xml");
            System.out.println("执行setResourceLoader:: Resource File Name="+ resource.getFilename());
        }
        @Override
        public void setImportMetadata(AnnotationMetadata annotationMetadata) {
            System.out.println("执行setImportMetadata");
        }
    
    }
    

    相关文章

      网友评论

        本文标题:Spring Aware 接口

        本文链接:https://www.haomeiwen.com/subject/xerkpctx.html