条件化创建Bean

前言

Spring 4提供了@Conditional,用来根据条件创建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,则实例化一个名为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();
    }
    
}

这样的话,在你提供了默认的实现之后,也可以通过定义一个实现类,名为payBusService,来覆盖默认的实现。

结后语

你可能感兴趣的:(条件化创建Bean)