Spring @PostConstruct depending on @Profile

二次信任 提交于 2019-12-10 13:48:22

问题


I'd like to have multiple @PostConstruct annotated methods in one configuration class, that should be called dependent on the @Profile. You can imagine a code snipped like this:

@Configuration
public class SilentaConfiguration {

    private static final Logger LOG = LoggerFactory.getLogger(SilentaConfiguration.class);

    @Autowired
    private Environment env;

    @PostConstruct @Profile("test")
    public void logImportantInfomationForTest() {
        LOG.info("********** logImportantInfomationForTest");
    }

    @PostConstruct @Profile("development")
    public void logImportantInfomationForDevelopment() {
        LOG.info("********** logImportantInfomationForDevelopment");
    }   
}

However according to the javadoc of @PostConstruct I can only have one method annotated with this annotation. There is an open improvement for that in Spring's Jira https://jira.spring.io/browse/SPR-12433.

How do you solved this requirement? I can always split this configuration class into multiple classes, but maybe you have a better idea/solution.

BTW. The code above runs without problems, however both methods are called regardless of the profile settings.


回答1:


I solved it with one class per @PostConstruct method. (This is Kotlin but it translates to Java almost 1:1.)

@SpringBootApplication
open class Backend {

    @Configuration
    @Profile("integration-test")
    open class IntegrationTestPostConstruct {

        @PostConstruct
        fun postConstruct() {
            // do stuff in integration tests
        }

    }

    @Configuration
    @Profile("test")
    open class TestPostConstruct {

        @PostConstruct
        fun postConstruct() {
            // do stuff in normal tests
        }

    }

}



回答2:


You can check for profile with Environment within a single @PostContruct.

An if statement would do the trick.

Regards, Daniel



来源:https://stackoverflow.com/questions/36220273/spring-postconstruct-depending-on-profile

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