Spring @PostConstruct取决于@Profile

时间:2016-03-25 12:49:50

标签: 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中有一个开放的改进。

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

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

2 个答案:

答案 0 :(得分:8)

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

    }

}

答案 1 :(得分:4)

您可以在一个Environment内查看包含@PostContruct的个人资料。

if语句可以解决问题。

此致 丹尼尔