【问题标题】:Spring @PostConstruct depending on @ProfileSpring @PostConstruct 取决于 @Profile
【发布时间】:2016-03-25 12:49:49
【问题描述】:

我想在一个配置类中有多个@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 中有一个公开的改进。

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

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

【问题讨论】:

  • 自己动手吧。 Environment 可以告诉您配置文件是否处于活动状态。所以创建一个简单的 if 语句。
  • 或将你的班级分成两部分,每一部分都在班级级别标注正确的@Profile
  • 投给这个问题的朋友:jira.spring.io/browse/SPR-12433

标签: java spring configuration postconstruct


【解决方案1】:

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

    }

}

【讨论】:

    【解决方案2】:

    您可以在单个@PostContruct 中使用Environment 检查个人资料。

    if 语句可以解决问题。

    问候, 丹尼尔

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2016-07-13
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2021-11-15
      • 2015-09-25
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多