Spring @PostConstruct取决于@Profile

我想在一个配置类中有多个@PostConstruct注释的方法,这应该被称为依赖于@Profile。 你可以想象一个代码如下所示:

@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"); } } 

但是根据@PostConstruct的javadoc,我只能使用这个注释来注释一个方法。 在Spring的Jira https://jira.spring.io/browse/SPR-12433中有一个改进。

你如何解决这个要求? 我总是可以将这个配置类分成多个类,但也许你有一个更好的主意/解决方案。

BTW。 上面的代码运行没有问题,但是无论配置文件设置如何,都会调用这两个方法。

您可以在一个@PostContruct检查Environment配置文件。

一个if语句可以做到这一点。

问候,丹尼尔

我用@PostConstruct方法一个类来解决它。 (这是Kotlin,但它转换为Java几乎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 } } }