java - Spring @PostConstruct 依赖于@Profile

标签 java spring configuration postconstruct

我想在一个配置类中有多个@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 .

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

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

最佳答案

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

    }

}

关于java - Spring @PostConstruct 依赖于@Profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36220273/

相关文章:

java - eclipse:未使用的私有(private)方法没有警告

java - Hibernate 4.1 错误 : Could not create DynamicParameterizedType for type: org. hibernate.type.EnumType

c# - 将 IConfiguration 注入(inject)到 .NET 6.0 上的 Windows 窗体

java - 从导入的依赖项覆盖 Gradle 项目配置

java - 如何使用用户标识检索和显示图像

java - 获取多部分/表单上传进度的替代方法 (Android)

java - Android 创建显示 View

java - hibernate : Lock a row while update, 所以用户不会从中检索计数器

java - 创建项目之间的依赖关系

php - Magento 自定义模块如何在 config.xml 中存储变量