2016-10-04 3 views
16

Есть ли способ, мы можем объявить Весенний боб условно нравится:Можем ли мы условно объявить фасоль весны?

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

Было бы полезно, вместо того, чтобы использовать профили. У меня нет конкретного случая использования, но он пришел ко мне.

ответ

14

Вы можете использовать @Conditional с весны или @ConditionalOnProperty от Spring ботинке.

  • 1.Using Spring4 (только),

    если вы НЕ с помощью пружины загрузки, это может быть излишним.

Во-первых, создать класс Condition, в котором ConditionContext имеет доступ к среде:

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 
@Conditional(MyCondition.class) 
public ObservationWebSocketClient observationWebSocketClient(){ 
    //return bean 
} 
  • 2.Using Spring Ботинки:

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

И в файле abcd.properties,

server.host=localhost 
0

У меня есть фрагмент кода для такой вещи. Он проверяет значение свойства, которое устанавливается в аннотации, так что вы можете использовать такие вещи, как

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

Он даже позволяет определить различные бобы с таким же названием:

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

Эти две банки быть объявлен в то же время, что позволяет иметь "service" имя боба с разными реализациями в зависимости от того, свойства включено или выключено ...

сниппета для него самого по себе:

/** 
* 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; 
    } 
} 
+0

Ах. Аннотация основе. Это абсолютно идеально. Я забыл аннотации, но есть ли способ сделать то же самое в Spring XML? –

+0

Хммм ... Google дал мне http://robertmaldon.blogspot.nl/2007/04/condition-defining-spring-beans.html, который выглядит так, как будто это можно сделать (хотя я не уверен, какая версия Spring используется в этом примере, так как он * совершенно * старый) –

Смежные вопросы