【问题标题】:Multiple negated profiles多个否定配置文件
【发布时间】:2015-01-23 15:31:57
【问题描述】:

我的问题是我有使用 Spring 配置文件的应用程序。在服务器上构建应用程序意味着配置文件设置为“wo-data-init”。对于其他版本,有“test”配置文件。当它们中的任何一个被激活时,它们不应该运行 Bean 方法,所以我认为这个注释应该可以工作:

@Profile({"!test","!wo-data-init"})

它看起来更像是在运行 if(!test OR !wo-data-init),而在我的情况下,我需要它运行 if(!test AND !wo-data-init) - 甚至可能吗?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    在 Spring 5.1.4 (Spring Boot 2.1.2) 及更高版本中,它很简单:

    @Component
    @Profile("!a & !b")
    public class MyComponent {}
    

    参考:How to conditionally declare Bean when multiple profiles are not active?

    【讨论】:

      【解决方案2】:

      我找到了更好的解决方案

      @Profile("default")
      

      配置文件默认意味着没有 foo 和没有 bar 配置文件。

      【讨论】:

      【解决方案3】:

      Spring 4 为 conditional bean creation 带来了一些很酷的功能。在您的情况下,确实简单的 @Profile 注释是不够的,因为它使用 OR 运算符。

      您可以做的一个解决方案是为其创建自定义注释和自定义条件。例如

      @Retention(RetentionPolicy.RUNTIME)
      @Target({ElementType.TYPE, ElementType.METHOD})
      @Documented
      @Conditional(NoProfilesEnabledCondition.class)
      public @interface NoProfilesEnabled {
          String[] value();
      }
      
      public class NoProfilesEnabledCondition implements Condition {
      
          @Override
          public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              boolean matches = true;
      
              if (context.getEnvironment() != null) {
                  MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(NoProfileEnabled.class.getName());
                  if (attrs != null) {
                      for (Object value : attrs.get("value")) {
                          String[] requiredProfiles = (String[]) value;
      
                          for (String profile : requiredProfiles) {
                              if (context.getEnvironment().acceptsProfiles(profile)) {
                                  matches = false;
                              }
                          }
      
                      }
                  }
              }
              return matches;
          }
      }
      

      以上是对ProfileCondition的快速而肮脏的修改。

      现在你可以用这种方式注释你的 bean:

      @Component
      @NoProfilesEnabled({"foo", "bar"})
      class ProjectRepositoryImpl implements ProjectRepository { ... }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 2011-01-05
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多