1. 程式人生 > >子類會呼叫父類的@PostConstruct方法

子類會呼叫父類的@PostConstruct方法

如果一個類用@Service 或 @Component,那麼只需要用@PostConstruct修飾某個方法,該方法能在類例項化的過程中自動執行,相當於類的建構函式。同時,具備了建構函式不具備的功能。

@Service
class Test{
    @PostConstruct
    public void sayHello(){
        System.out.println("Hello!");
    }
}

但是需要注意:

子類例項化過程中會呼叫父類中的@PostConstruct方法!

@Service 
class TestChild extends Test{
    @PostConstruct
public void sayBye(){ System.out.println("Bye!"); } }

啟動專案,輸出如下:
Hello!
Bye!