- @PostConstruct 構造後置執行
- @Bean(initMethod="xxx") 初始化功能
- @InitializingBean#afterPropertiesSet 屬性填充後執行
DefaultRumenzFactory.javahtml
package com.rumenz; import org.springframework.beans.factory.InitializingBean; import javax.annotation.PostConstruct; public class DefaultRumenzFactory implements InitializingBean { public DefaultRumenzFactory() { System.out.println("無參構造方法執行...."); } @PostConstruct public void init(){ System.out.println("PostConstruct init......."); } public void initMethod(){ System.out.println("init method......."); } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet....."); } }
DemoApplication.java調用java
package com.rumenz; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; public class DemoApplication { public static void main(String[] args) { AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(); ac.register(DemoApplication.class); ac.refresh(); DefaultRumenzFactory bean = ac.getBean(DefaultRumenzFactory.class); ac.close(); } @Bean(initMethod = "initMethod") public static DefaultRumenzFactory defaultRumenzFactory(){ return new DefaultRumenzFactory(); } }
輸出git
xxx.DefaultListableBeanFactory - Creating shared instance of singleton bean 'defaultRumenzFactory' 無參構造方法執行.... PostConstruct init....... afterPropertiesSet..... init method.......
執行順序github
- 1.@PostConstruct
- 2.@InitializingBean#afterPropertiesSet
- 3.@Bean(initMethod="xxx")
源碼:https://github.com/mifunc/Spring-BeanInitializationspring
原文: https://rumenz.com/rumenbiji/Spring-BeanInitialization.htmlide