Reputation: 58772
I'm using spring applications which sometimes uses @PostConstruct
for setup in code and tests
It seems that annotation will be excluded from Java 11:
Note that both @PostConstruct and @PreDestroy annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations
Article suggest replacing all @PostConstruct
with afterPropertiesSet
method
I recommend you to change implementation from @PostConstruct annotation to implement org.springframework.beans.factory.InitializingBean interface.
Can I blindly replace it in all cases? or are there other considerations?
EDIT
As @JBNizet suggested, this maybe not a must or needed, as Spring doc suggest the opposite
We recommend that you do not use the InitializingBean interface, because it unnecessarily couples the code to Spring. Alternatively, we suggest using the @PostConstruct annotation or specifying a POJO initialization method.
EDIT 2
Another option is using initMethod
:
With Java configuration, you can use the initMethod attribute of @Bean
@Bean(initMethod = "init") public BeanOne beanOne() { return new BeanOne(); }
Upvotes: 11
Views: 20319
Reputation: 120858
Spring uses jakarta.annotation.PostConstruct
. As a contributor in spring-cloud-kubernetes
, I have used it and included it in that project numerous times. As a matter of fact we favor dropping InitializingBean
.
Upvotes: 5
Reputation: 2752
Like @Resource, the @PostConstruct and @PreDestroy annotation types were a part of the standard Java libraries from JDK 6 to 8. However, the entire javax.annotation package got separated from the core Java modules in JDK 9 and eventually removed in JDK 11. If needed, the javax.annotation-api artifact needs to be obtained via Maven Central now, simply to be added to the application’s classpath like any other library.
Upvotes: 0