Spring 条件装配

定义

从Spring Framework 3.1开始,允许Bean 装配时增加前置条件判断

判断方式

@Profile: 配置化条件装配,Spring Framework 3.1
@Conditional:编程条件装配,Spring Framework 4.0

实现方式
  • 注解方式-- @Profile
首先定义一个接口
/**
 * 计算整数求和
 */
public interface CalculateService {

    Integer sum(Integer... values);
}

分别用两个实现类去实现,在类上使用 `@Profile`注解进行配置
@Profile("java7")
@Service
public class Java7CalculateServiceImpl implements CalculateService {}


@Profile("java8")
@Service
public class Java8CalculateServiceImpl implements CalculateService {}

在进行服务的调用时使用 profiles 的方式进行指定
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(CalculateServiceBootStrap.class)
                .web(WebApplicationType.NONE)
                .profiles("java7")
                .run(args);
                
       // 这种方式如果没有指定profile,会出现异常(NoSuchBeanDefinitionException: No qualifying bean of type *** available)
        CalculateService calculateService = context.getBean(CalculateService.class); 
     }
  • 编程方式
    上面描述的profile注解实现方式,从注解的定义上可以看到,他的底层就是用@Conditional实现的,而ProfileCondition类是通过实现Condition接口的matches方法,在这个方法中通过编程条件进行过滤,返回true即可对使用了Profile注解的类进行装配
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
    String[] value();
}

class ProfileCondition implements Condition {
    ProfileCondition() {
    }

    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
        if (attrs != null) {
            Iterator var4 = ((List)attrs.get("value")).iterator();

            Object value;
            do {
                if (!var4.hasNext()) {
                    return false;
                }

                value = var4.next();
            } while(!context.getEnvironment().acceptsProfiles(Profiles.of((String[])((String[])value))));

            return true;
        } else {
            return true;
        }
    }
}

结合上面的这个实现下面进行手工的配置,仿造上面实现的方法:

1.新建类实现 Condition接口的matches方法

public class HelloWorldCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
    	// 这里的annotatedTypeMetadata可以获取指定类的一些属性(TestCondition是我自己新建的一个注解)
        Map<String, Object> attrs = annotatedTypeMetadata.getAnnotationAttributes(TestCondition.class.getName());
        // 这里是获取这个注解的属性
        String name = String.valueOf(attrs.get("name"));
        String value = String.valueOf(attrs.get("value"));
        // 这里我直接获取了系统配置的值,用来进行判断
        String propertyName = System.getProperty(name);
        return propertyName.equals(value);
    }
}
  1. 新建注解,使用@Conditional去关联上面的HelloWorldCondition实现,来进行条件的判断
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({HelloWorldCondition.class})
public @interface TestCondition {
    String name();
    String value();
}
  1. 使用注解,放在需要被装配上,这里我放在了一个bean上
    @Bean
    // name 设置成user.name是为了配合上面的获取系统配置的user.name的值,后面的value值会和系统的name值进行判断,如果相同matches方法就会返回true,这样就能将helloWorld这个bean进行自动装配
    @TestCondition(name = "user.name", value = "Administrator")
    public String helloWorld() {
        return "Hello, World";
    }
  1. 验证是否装配成功
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(HelloWorldConditionBootStrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        // 上面如果通过注解成功进行条件筛选后,容器中是可以直接获取到helloWorld这个bean的,如果能够输出helloWorld返回的值就说明装配成功了
        String helloWorld = context.getBean("helloWorld", String.class);
        System.out.println("helloWorld:" + helloWorld);
        context.close();
    }
  1. 假设上面的注解中使用了不匹配的value值,看看报什么错:
    @Bean
    @TestCondition(name = "user.name", value = "Administrator1")
    public String helloWorld() {
        return "Hello, World";
    }
   // 这里在value后面加了一个1,应该和系统默认名称不匹配的,此时启动后出现报错如下:
   NoSuchBeanDefinitionException: No bean named 'helloWorld' available
   此时说明没有装配需要的Bean
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值