【问题标题】:Can we declare spring bean conditionally?我们可以有条件地声明spring bean吗?
【发布时间】:2016-10-04 16:52:05
【问题描述】:

有没有一种方法可以有条件地声明一个 Spring bean,例如:

<bean class="path.to.the.class.MyClass" if="${1+2=3}" />

它会很有用,而不必使用配置文件。 我没有想到具体的用例,但我想到了。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您可以使用 Spring4 中的 @Conditional 或 Spring Boot 中的 @ConditionalOnProperty。

    1. 使用 Spring4(仅)

    如果您不使用 Spring Boot,那么这可能是矫枉过正。

    首先,创建一个Condition 类,其中ConditionContext 可以访问Environment:

    public class MyCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context,
                               AnnotatedTypeMetadata metadata) {
            Environment env = context.getEnvironment();
            return null != env
                    && "true".equals(env.getProperty("server.host"));
        }
    }
    

    然后注释你的bean:

    @Bean
    @Conditional(MyCondition.class)
    public ObservationWebSocketClient observationWebSocketClient() {
        //return bean
    }
    

    2.使用SpringBoot:

    @ConditionalOnProperty(name="server.host", havingValue="localhost")
    

    在您的abcd.properties 文件中,

    server.host=localhost
    

    【讨论】:

      【解决方案2】:

      对于这样的事情,我有一个 sn-p。它检查注释中设置的属性的值,因此您可以使用类似

      @ConditionalOnProperty(value="usenew", on=false, propertiesBeanName="myprops")
      @Service("service")
      public class oldService implements ServiceFunction{
          // some old implementation of the service function.
      }
      

      它甚至允许您定义具有相同名称的不同 bean:

      @ConditionalOnProperty(value="usenew", on=true, propertiesBeanName="myprops")
      @Service("service")
      public class newService implements ServiceFunction{
          // some new implementation of the service function.
      }
      

      这两个可以同时声明,允许你有一个"service"命名的bean,根据属性是打开还是关闭,实现不同...

      它本身的sn-p:

      /**
       * Components annotated with ConditionalOnProperty will be registered in the spring context depending on the value of a
       * property defined in the propertiesBeanName properties Bean.
       */
      
      @Target({ ElementType.TYPE, ElementType.METHOD })
      @Retention(RetentionPolicy.RUNTIME)
      @Conditional(OnPropertyCondition.class)
      public @interface ConditionalOnProperty {
          /**
           * The name of the property. If not found, it will evaluate to false.
           */
          String value();
          /**
           * if the properties value should be true (default) or false
           */
          boolean on() default true;
          /**
           * Name of the bean containing the properties.
           */
          String propertiesBeanName();
      }
      
      /**
       * Condition that matches on the value of a property.
       *
       * @see ConditionalOnProperty
       */
      class OnPropertyCondition implements ConfigurationCondition {
          private static final Logger LOG = LoggerFactory.getLogger(OnPropertyCondition.class);
      
          @Override
          public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
              final Map attributes = metadata.getAnnotationAttributes(ConditionalOnProperty.class.getName());
              final String propertyName = (String) attributes.get("value");
              final String propertiesBeanName = (String) attributes.get("propertiesBeanName");
              final boolean propertyDesiredValue = (boolean) attributes.get("on");
      
              // for some reason, we cannot use the environment here, hence we get the actual properties bean instead.
              Properties props = context.getBeanFactory().getBean(propertiesBeanName, Properties.class);
              final boolean propValue = parseBoolean(props.getProperty(propertyName, Boolean.toString(false)));
              LOG.info("Property '{}' resolved to {}, desired: {}", new Object[] { propertyName, propValue, "" + propertyDesiredValue });
              return propValue == propertyDesiredValue;
          }
          /**
           * Set the registration to REGISTER, else it is handled during  the parsing of the configuration file
           * and we have no guarantee that the properties bean is loaded/exposed yet
           */
          @Override
          public ConfigurationPhase getConfigurationPhase() {
              return ConfigurationPhase.REGISTER_BEAN;
          }
      }
      

      【讨论】:

      • 啊。基于注释。那绝对是完美的。我忘记了注释,但是有没有办法在 Spring XML 中做同样的事情?
      • 嗯...谷歌给了我robertmaldon.blogspot.nl/2007/04/…,看起来也可以做到(尽管我不确定该示例中使用的是哪个版本的 Spring,因为它是 相当老)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 2017-04-11
      • 2016-12-06
      • 2019-09-02
      • 1970-01-01
      • 2018-07-26
      相关资源
      最近更新 更多