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 } } }
- 带有Jetty + Jersey的Spring Boot始终显示404
- IntelliJ Idea for Kotlin @ConfigurationProperties类中不生成spring-configuration-metadata.json文件
- Kotlin协程和Spring Framework 5反应类型
- 如何将IoC注入到Kotlin顶级函数中? 我甚至使用IoC容器?
- 测试Spring的@Async void返回方法
- Java Stream with :: new to Kotlin
- Spring Boot和Kotlin中的部分更新REST
- Spring REST,Kotin和默认的基本参数导致错误
- 如何使用onErrorMap()处理异常时如何访问Mono <T>?