[关闭]
@survivorZzz 2018-10-17T03:47:52.000000Z 字数 1092 阅读 2178

代码块 静态代码块 引申出Spring 中InitializingBean 接口和@PostConstruct的作用

Spring java


有这样一个bean定义:

  1. public class MyClass implements InitializingBean {
  2. static {
  3. System.err.println(">>>>>>>>> static block");
  4. }
  5. {
  6. System.err.println(">>>>>>>>> non-static block");
  7. }
  8. @Override
  9. public void afterPropertiesSet() throws Exception {
  10. System.err.println(">>>>>>>>> afterPropertiesSet method!");
  11. }
  12. @PostConstruct
  13. void method() {
  14. System.err.println(">>>>>>>>> postConstruct method!");
  15. }
  16. }

SpringBoot 启动类中向容器中注入MyCalssBean

  1. @SpringBootApplication
  2. public class DemoApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(DemoApplication.class, args);
  5. MyClass myClass = new MyClass();
  6. }
  7. @Bean
  8. public MyClass newMyClass() {
  9. return new MyClass();
  10. }
  11. }

亲测, 输出顺序:

  1. >>>>>>>>> static block
  2. >>>>>>>>> non-static block
  3. >>>>>>>>> postConstruct method!
  4. >>>>>>>>> afterPropertiesSet method!
  5. >>>>>>>>> non-static block

结论:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注