【问题标题】:Spring @Profile works on class, but not on @BeanSpring @Profile 适用于类,但不适用于 @Bean
【发布时间】:2015-11-03 19:39:43
【问题描述】:

我无法让@Profile@Bean 上工作,但它在@Configuration 类上工作正常。在我的模块测试中,我在第一个示例中正确获得了 MyServiceStub 自动装配,但在第二个示例中没有。

有人知道为什么吗?

这行得通:

MyConfig.java

@Configuration
@Import({StubConfig.class, RealConfig.class}
public class MyConfig {}

StubConfig.java

@Profile({"featureTest", "moduleTest"})
@Configuration
public class StubConfig {

  @Bean
  public MyService myService() {
    return new MyServiceStub();
  }
}

RealConfig.java

@Profile({"!featureTest", "!moduleTest"})
@Configuration
public class RealConfig {

  @Bean
  public MyService myService() {
    return new MyService();
  }
}

但这不起作用:

MyConfig.java

@Configuration
public class MyConfig {

  @Bean
  @Profile({"featureTest", "moduleTest"})
  public MyService myServiceStub() {
    return new MyServiceStub();
  }

  @Bean
  @Profile({"!featureTest", "!moduleTest"})
  public MyService myService() {
    return new MyService();
  }
}

【问题讨论】:

  • 您是否有一个名为"!moduleTest" 的明确个人资料?
  • 一直在为我工作,但我没有使用花括号。你能试着去掉花括号看看吗?
  • @Sanjay:这就是声明具有多个值的注释的方式。 @Profile 的值是 String[],因此如果数组中有一个元素,则大括号是隐式的。
  • @Makato:是的。它一直对我有用,所以我只是要求确认。 (我有一个非常相似的例子,包括!,这意味着不是。)
  • @Makato No. "!moduleTest" 的意思是“不是 moduleTest”。

标签: java spring spring-mvc


【解决方案1】:

您可以尝试使用@Conditional 来创建conditional bean,而不是使用@Profile 方法。

或者有一个明确的if-stmt 来检查activeProfile 是什么。您可以根据 activeProfile 创建 Bean 实例。我认为这种方法可以反映在 Spring XML 中使用他们的表达式语言可以完成的工作。但@Conditional 似乎更适合您。

【讨论】:

  • 您的答案以“我不确定”开头,但 easy to verify 允许在 @Profile 前加上 !对于“NOT”,它也可以用于@Bean-annotated 方法。看起来 OP 的问题没有包含足够的信息来诊断问题。使用@Conditional 重新实现@Profile 行为而不是深入问题的根源感觉像是一种懒惰的解决方法。
猜你喜欢
  • 2021-11-15
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多