Spring的@PostConstruct如何依赖于@Profile?

10

我希望在一个配置类中拥有多个被@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

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

顺便说一句,上面的代码运行良好,但无论配置文件设置如何,两种方法都会被调用。


1
自己动手做。Environment 可以告诉你配置文件是否处于活动状态。因此,创建一个简单的 if 语句即可。 - M. Deinum
或将您的类拆分为两部分,每个部分都应在类级别上正确注释@Profile。 - Ruben
投票支持这个问题:https://jira.spring.io/browse/SPR-12433 - Rafal G.
2个回答

17

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

    }

}

工作得很好,有趣的是,当我在我的普通的@Configuration @PostConstruct方法中添加一个@Profile(...)时,它被忽略了。然而,子类化是有效的,并且允许您同时触发多个PostConstruct(如果您真的想要的话)。不确定是否符合规范(https://jakarta.ee/specifications/platform/10/apidocs/jakarta/annotation/postconstruct)。 - undefined

9

您可以在单个@PostContruct中使用Environment检查配置文件。

使用if语句即可实现。

祝好, Daniel


你可以加一个例子吗? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接