Bean 初始化
Spring 中初始化 bean 的方法 1. 使用 @PostConstruct (較常用) 2. 實現 InitializingBean interface 的 afterPropertiesSet() 方法
@PostConstruct
@Component 創建 bean ,Printer hpPrinter = new HpPrinter();
count 預設為 0
如果我們想用 @PostConstruct 初始化 count 這個變數
要先寫一個方法 ,在上面加上 @PostConstruct
@Component
public class HpPrinter implements Printer{
private int count;
@PostConstruct
public void initialize(){
count = 5;
}
@Override
public void print(String msg){
count--;
System.out.println("Hp印表機: " + msg);
System.out.println("剩餘使用次數: " + count);
}
}

實現 InitializingBean interface
先實作 InitializingBean 這個 interface
實現他的方法 afterPropertiesSet() ,將要初始化的變數寫在方法裡面
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
// step1: 要先實作 InitializingBean 這個interface
public class Hp2Printer implements Printer ,InitializingBean {
private int count;
// step2: 實現他的方法 afterPropertiesSet() ,將要初始化的變數寫在方法裡面
@Override
public void afterPropertiesSet() throws Exception {
count = 5;
}
@Override
public void print(String msg) {
System.out.println("Hp印表機: " + msg);
System.out.println("剩餘使用次數: " + count);
}
}
-
@PostConstruct 跟 InitializingBean interface 擇一使用就好
-
因為沒有辦法確定哪個初始化的方法會先被執行
Bean 初始化的練習
在 HpPrinter 的 class 中加入一個count 的變數
然後初始化 count 預設值改成 5
因為目前只有一個 @Component
所以 MyController 中 @Autowired 的 Printer 不需要用@Qualifier 來指定 bean
在網址上輸入 localhost:8080/test
