2016-10-04 13 views

Trả lời

14

Bạn có thể sử dụng @Conditional từ mùa xuân hoặc @ConditionalOnProperty từ mùa xuân Boot.

  • 1.Sử dụng Spring4 (chỉ),

    nếu bạn đang KHÔNG sử dụng lò xo boot, này có thể là quá mức cần thiết.

Đầu tiên, tạo một lớp Điều kiện, trong đó ConditionContext có quyền truy cập vào các môi trường:

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")); 
    } 
} 

Sau đó, chú thích đậu của bạn:

@Bean 
@Conditional(MyCondition.class) 
public ObservationWebSocketClient observationWebSocketClient(){ 
    //return bean 
} 
  • 2.Using Xuân Khởi động:

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

Và trong tập tin abcd.properties của bạn,

server.host=localhost 
0

Tôi có một đoạn cho một điều như vậy. Nó kiểm tra giá trị của một tài sản được thiết lập trong chú thích, vì vậy bạn có thể sử dụng những thứ như

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

Nó thậm chí cho phép bạn xác định đậu khác nhau có cùng tên:

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

Hai lon được khai báo cùng một lúc, cho phép bạn có một bean được đặt tên là "service" với các cách triển khai khác nhau tùy thuộc vào việc tài sản đang bật hay tắt ...

Đoạn mã cho chính nó:

/** 
* 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

Ah. Dựa trên chú thích. Điều đó hoàn toàn hoàn hảo. Tôi quên chú thích, nhưng có cách nào để làm tương tự trong Spring XML không? –

+0

Hmmm ... Một google đã cho tôi http://robertmaldon.blogspot.nl/2007/04/conditionally-defining-spring-beans.html trông giống như nó có thể được thực hiện là tốt (mặc dù tôi không chắc chắn phiên bản nào của Spring được sử dụng trong ví dụ đó, vì nó là * khá * cũ) –

Các vấn đề liên quan