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注解的標注的方法就會立即執行。

 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM