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

喜欢而已 提交于 2021-01-04 05:40:49

问题


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();
}

来源:https://stackoverflow.com/questions/55559332/java-11-replace-spring-postconstruct-with-afterpropertiesset-or-using-initmet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!