• spring探秘:通过BeanPostProcessor、@PostConstruct、InitializingBean在启动前执行方法


    springboot启动前执行方法的3种方式:实现BeanPostProcessor接口、实现InitializingBean接口、使用@PostConstruct注解

    示例:

    第一种 实现BeanPostProcessor接口

    @Configuration
    public class Test3 implements BeanPostProcessor {
    
        @Autowired
        private Environment environment;
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { String property = environment.getProperty("aaa.bbb"); System.out.println("test3"+property); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }
    }

    第二种 实现InitializingBean接口

    @Configuration
    public class Test2 implements InitializingBean {
    
        @Autowired
        private Environment environment;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            String property = environment.getProperty("aaa.bbb");
            System.out.println("test2"+property);
        }
    
    }

    第三种 使用@PostConstruct注解

    @Configuration
    public class Test1 {
    
        @Autowired
        private Environment environment;
    
        @PostConstruct
        public void test(){
            String property = environment.getProperty("aaa.bbb");
            System.out.println("test1"+property);
        }
    
    }

     运行的优先级是:

    启动类前->BeanPostProcessor->@PostConstruct->InitializingBean

    需注意:BeanPostProcessor的方式会让实现类里的方法提前执行。BeanPostProcessor为每一个spring维护的对象调用前后做操作,实现了它我们当前类就会变成一个BeanPostProcessor对象,就可以像BeanPostProcessor一样在容器加载最初的几个阶段被实例化,只要被实例化,PostConstruct注解的标注的方法就会立即执行。

     
     
  • 相关阅读:
    spoj694 DISUBSTR
    poj3261 Milk Patterns
    poj1743 Musical Theme
    Hdu1403 Longest Common Substring
    bzoj3779 重组病毒
    bzoj3083 遥远的国度
    bzoj3514 Codechef MARCH14 GERALD07加强版
    PAT 乙级 1027 打印沙漏(20) C++版
    PAT 乙级 1060 爱丁顿数(25) C++版
    windows编程之窗口抖动
  • 原文地址:https://www.cnblogs.com/feng-gamer/p/12001205.html
Copyright © 2020-2023  润新知