gpt4 book ai didi

java - Spring @PostConstruct 依赖于@Profile

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:57 24 4
gpt4 key购买 nike

我想在一个配置类中有多个@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 .

你是如何解决这个需求的?我总是可以将此配置类拆分为多个类,但也许您有更好的想法/解决方案。

顺便说一句。上面的代码运行没有问题,但是无论配置文件设置如何,这两种方法都会被调用。

最佳答案

我用每个 @PostConstruct 方法用一个类解决了它。 (这是 Kotlin,但它几乎以 1:1 的比例转换为 Java。)

@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
}

}

}

关于java - Spring @PostConstruct 依赖于@Profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36220273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com