Spring @PostConstruct取决于@Profile

Ada*_*zek 5 java configuration spring 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");
    }   
}
Run Code Online (Sandbox Code Playgroud)

但是根据@PostConstruct的javadoc,我只能有一个用这个注释注释的方法.在Spring的Jira https://jira.spring.io/browse/SPR-12433中有一个开放的改进.

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

BTW.上面的代码运行没有问题,但无论配置文件设置如何,都会调用这两种方法.

Bom*_*mbe 9

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

    }

}
Run Code Online (Sandbox Code Playgroud)


Dan*_*oie 5

您可以Environment在单个@PostContruct.

一个if声明会做的伎俩。

问候, 丹尼尔