Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 11 - Replace Spring @PostConstruct with afterPropertiesSet or using initMethod

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();
}
like image 768
user7294900 Avatar asked Mar 16 '26 07:03

user7294900


2 Answers

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.

like image 173
Eugene Avatar answered Mar 18 '26 20:03

Eugene


Ref https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-postconstruct-and-predestroy-annotations

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.

like image 26
Anderson Avatar answered Mar 18 '26 21:03

Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!