若是一个类用@Service或@Component,那么只须要用@PostConstruct修饰某个方法,该方法能在类实例化的过程当中自动执行,至关于类的构造函数。同时,具有了构造函数不具有的功能。框架
@Component class Test{ @PostConstruct public void sayHello(){ System.out.println("Hello!"); } }
可是须要注意:函数
子类实例化过程当中会调用父类中的@PostConstruct方法。spa
@Component class TestChild extends Test{ @PostConstruct public void sayBye(){ System.out.println("Bye!"); } }
启动项目,输出以下:.net
Hello!
Bye!
转载自《慎用Spring框架-子类会调用父类的@PostConstruct方法》code