Spring @PostConstruct depending on @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,我只能有一个方法用这个注释进行注释。《春天的吉拉》对此有一个公开的改进https://jira.spring.io/browse/SPR-12433.

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

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

我用每个@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
        }
    }
}

您可以在单个@PostContruct中检查具有Environment的配置文件。

if语句就可以了。

谨致问候,Daniel

最新更新