本文介绍了Spring @PostConstruct取决于@Profile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个配置类中有多个@PostConstruct注释方法,应根据@Profile进行调用.您可以想像这样的代码片段:

I'd like to have multiple @PostConstruct annotated methods in one configuration class, that should be called dependent on the @Profile. You can imagine a code snipped like this:

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

However according to the javadoc of @PostConstruct I can only have one method annotated with this annotation. There is an open improvement for that in Spring's Jira https://jira.spring.io/browse/SPR-12433.

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

How do you solved this requirement? I can always split this configuration class into multiple classes, but maybe you have a better idea/solution.

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

BTW. The code above runs without problems, however both methods are called regardless of the profile settings.

推荐答案

我用每个@PostConstruct方法的一个类解决了它. (这是Kotlin,但几乎翻译成了Java 1:1.)

I solved it with one class per @PostConstruct method. (This is Kotlin but it translates to Java almost 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
        }

    }

}

这篇关于Spring @PostConstruct取决于@Profile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 17:04