简体   繁体   English

Spring @PostConstruct取决于@Profile

[英]Spring @PostConstruct depending on @Profile

I'd like to have multiple @PostConstruct annotated methods in one configuration class, that should be called dependent on the @Profile. 我想在一个配置类中有多个@PostConstruct注释方法,应该根据@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");
    }   
}

However according to the javadoc of @PostConstruct I can only have one method annotated with this annotation. 但是根据@PostConstruct的javadoc,我只能有一个用这个注释注释的方法。 There is an open improvement for that in Spring's Jira https://jira.spring.io/browse/SPR-12433 . 在Spring的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. BTW。 The code above runs without problems, however both methods are called regardless of the profile settings. 上面的代码运行没有问题,但无论配置文件设置如何,都会调用这两种方法。

I solved it with one class per @PostConstruct method. 我用@PostConstruct方法用一个类解决了它。 (This is Kotlin but it translates to Java almost 1:1.) (这是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
        }

    }

}

You can check for profile with Environment within a single @PostContruct . 您可以在单个@PostContruct检查Environment中的配置文件。

An if statement would do the trick. if语句可以解决这个问题。

Regards, Daniel 问候,丹尼尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM