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