前言
Spring 4提供了@Conditional品姓,用來根據(jù)條件創(chuàng)建Bean距境,具體用法如下:
開始
首先习寸,自定義條件類BusServiceExistsCondition,該類是判斷如果上下文中存在名為payBusService的Bean惦界,則返回false挑格。
package com.asiainfo.aigov.plugins.pay;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class BusServiceExistsCondition implements Condition {
static final String BUS_SERVICE_BEAN_NAME = "payBusService";
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !context.getBeanFactory().containsBean(BUS_SERVICE_BEAN_NAME);
}
}
然后,在配置類BusServiceConfig中沾歪,如果該條件判斷為true漂彤,則實(shí)例化一個(gè)名為payBusService的Bean。
package com.asiainfo.aigov.plugins.pay;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import com.asiainfo.aigov.plugins.pay.service.BusService;
import com.asiainfo.aigov.plugins.pay.service.IBusService;
@Configuration
public class BusServiceConfig {
@Conditional(BusServiceExistsCondition.class)
@Bean(name=BusServiceExistsCondition.BUS_SERVICE_BEAN_NAME)
public IBusService busService() {
return new BusService();
}
}
這樣的話灾搏,在你提供了默認(rèn)的實(shí)現(xiàn)之后挫望,也可以通過定義一個(gè)實(shí)現(xiàn)類,名為payBusService确镊,來覆蓋默認(rèn)的實(shí)現(xiàn)士骤。
結(jié)后語
略