Spring @PostConstruct vs. init-method attribute

前端 未结 6 894
攒了一身酷
攒了一身酷 2020-12-04 06:35

Is there any difference between using the @PostConstruct annotation and declaring the same method as init-method in Spring XML configuration?

6条回答
  •  攒了一身酷
    2020-12-04 07:16

    Full code here: https://github.com/wkaczurba/so8519187 (spring-boot)

    Using annotations:

    @Slf4j
    @Component
    public class MyComponent implements InitializingBean {
    
        @Value("${mycomponent.value:Magic}")
        public String value;
    
        public MyComponent() {
            log.info("MyComponent in constructor: [{}]", value); // (0) displays: Null
        }
    
        @PostConstruct
        public void postConstruct() {
            log.info("MyComponent in postConstruct: [{}]", value); // (1) displays: Magic
        }
    
        @Override // init-method; overrides InitializingBean.afterPropertiesSet()
        public void afterPropertiesSet() {
            log.info("MyComponent in afterPropertiesSet: [{}]", value);  // (2) displays: Magic
        }   
    
        @PreDestroy
        public void preDestroy() {
            log.info("MyComponent in preDestroy: [{}]", value); // (3) displays: Magic
        }
    }
    

    Gets us:

    Refreshing org.springframework.context...

    MyComponent in constructor: [null]
    MyComponent in postConstruct: [Magic]
    MyComponent in afterPropertiesSet: [Magic]
    ...

    Registering beans for JMX exposure on startup
    Started DemoApplication in 0.561 seconds (JVM running for 1.011)
    Closing org.springframework.context... Unregistering JMX-exposed beans on shutdown

    ...
    MyComponent in preDestroy: [Magic]

提交回复
热议问题