Spring Bean初始化的幾種方法以及執行順序


  • @PostConstruct 構造后置執行
  • @Bean(initMethod="xxx") 初始化功能
  • @InitializingBean#afterPropertiesSet 屬性填充后執行

DefaultRumenzFactory.java

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調用

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();
    }

}

輸出

xxx.DefaultListableBeanFactory - Creating shared instance of singleton bean 'defaultRumenzFactory'
無參構造方法執行....
PostConstruct init.......
afterPropertiesSet.....
init method.......

執行順序
1.@PostConstruct
2.@InitializingBean#afterPropertiesSet
3.@Bean(initMethod="xxx")

源碼:https://github.com/mifunc/Spring-BeanInitialization

原文: https://rumenz.com/rumenbiji/Spring-BeanInitialization.html


免責聲明!

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



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