Spring 条件装配

Spring 条件装配

简介

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

条件注解举例

注解 场景说明
@Profile 配置化条件装配
@Conditional 编程条件装配

实现方式

配置方式,@Profile

  1. 编写服务层接口
public interface CalculateService {
    /**
     * 从多个整数 sum 求和
     * @param values 多个整数
     * @return sum 累加值
     */
    Integer sum(Integer... values);
}
  1. 实现CalculateService接口,实现一(java7),添加@Profile("Java7")注解
@Profile("Java7")
@Service
public class Java7CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... values) {
        System.out.println("Java 7 for 循环实现 ");
        int sum = 0;
        for (int i = 0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
}
  1. 实现CalculateService接口,实现二(java8),添加@Profile("Java8")注解
@Profile("Java8")
@Service
public class Java8CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... values) {
        System.out.println("Java 8 Lambda 实现");
        int sum = Stream.of(values).reduce(0, Integer::sum);
        return sum;
    }
}
  1. 编写启动类测试,使用SpringApplicationBuilder类添加条件.profiles("Java8")
@SpringBootApplication(scanBasePackages = "com.imooc.diveinspringboot.service")
public class CalculateServiceBootstrap {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(CalculateServiceBootstrap.class)
                .web(WebApplicationType.NONE)
                .profiles("Java8")
                .run(args);
        // CalculateService Bean 是否存在
        CalculateService calculateService = context.getBean(CalculateService.class);
        System.out.println("calculateService.sum(1...10) : " +
                calculateService.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        // 关闭上下文
        context.close();
    }
}

编程方式,@Conditional

  1. 编写注解@ConditionalOnSystemProperty,添加@Conditional(OnSystemPropertyCondition.class)指明实现类
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {
    /**
     * Java 系统属性名称
     * @return
     */
    String name();
    /**
     * Java 系统属性值
     * @return
     */
    String value();
}
  1. 编写实现类,实现Condition接口,实现matches方法
public class OnSystemPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        String propertyName = String.valueOf(attributes.get("name"));
        System.out.println(propertyName);
        String propertyValue = String.valueOf(attributes.get("value"));
        System.out.println("value:" + propertyValue);
        String javaPropertyValue = System.getProperty(propertyName);
        System.out.println(javaPropertyValue);
        return propertyValue.equals(javaPropertyValue);
    }
}
  1. 编写启动测试类
public class ConditionalOnSystemPropertyBootstrap {
    @Bean
    @ConditionalOnSystemProperty(name = "user.name", value = "XXXX")
    public String helloWorld() {
        return "Hello,World";
    }
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        // 通过名称和类型获取 helloWorld Bean
        String helloWorld = context.getBean("helloWorld", String.class);

        System.out.println("helloWorld Bean : " + helloWorld);

        // 关闭上下文
        context.close();
    }
}
原文地址:https://www.cnblogs.com/fjf3997/p/13023836.html