条件装配(@Profile方式)

利用@Conditional注解实现条件装配(小马哥springBoot)

@Profile方式

首先介绍@Profile是因为@Profile是依靠@Conditional实现的

两种求和的方式(for循环方式和lambda方式,通过@Profile区别)

Calculate.java

public interface Calculate {
    Integer sum(Integer... num);
}

Java7Calculate.java

@Profile("java7")
@Component
public class Java7Calculate implements Calculate {
    @Override
    public Integer sum(Integer... nums) {
        System.out.println("java7 calculating");

        Integer result = 0;
        for (Integer num : nums) {
            result += num;
        }
        return result;
    }
}

Java8Calculate.java

@Profile("java8")
@Component
public class Java8Calculate implements Calculate {
    @Override
    public Integer sum(Integer... num) {
        System.out.println("java8 calculating");
        return Stream.of(num).reduce(0, Integer::sum);
    }
}

Learn02AnnotationconfigApplication.java

@SpringBootApplication(scanBasePackages = "com.xmg.learn02annotationconfig.calculate")
public class Learn02AnnotationconfigApplication {

    public static void main(String[] args) {
//  对springApplication进行自定义,其实SpringApplication.run()方法中,也是利用配置文件等先初始化SpringApplication对象,这部分小马哥后面有讲
        SpringApplication springApplication = new SpringApplicationBuilder(Learn02AnnotationconfigApplication.class)
                .web(WebApplicationType.NONE)
                .profiles("java8")
                .build(args);
        ConfigurableApplicationContext context = springApplication.run(args);

        Calculate ca = context.getBean(Calculate.class);
        System.out.println(ca.sum(1, 2, 3, 4, 5));
    }

}

启动时控制台输出如下:

...
The following profiles are active: java8
...
java8 calculating
15

实际上,@Profile从Spring3.1之后,其实现方式时依靠@Conditional注解实现的

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {

ProfileCondition.java

class ProfileCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
        if (attrs != null) {
            for (Object value : attrs.get("value")) {
                if (context.getEnvironment().acceptsProfiles(Profiles.of((String[]) value))) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

}

@Conditional方式

@CalConditional (仿照@Profile注解)

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(CalculateCondition.class)
public @interface CalConditional {
    String value();
}

CalculateCondition.java

public class CalculateCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //得到java的系统属性 myProfile,判断与注解中的value值是否相等,返回true代表将该类交由spirng容器管理,false则不管理
        String myProfile = System.getProperty("myProfile");

        Map map = metadata.getAnnotationAttributes(CalConditional.class.getName());
        String value = (String)map.get("value");

        return myProfile != null && myProfile.equals(value);
    }
}

Java7CalculateCondition.java

@CalConditional("java7")
@Component
public class Java7CalculateCondition implements Calculate {
    @Override
    public Integer sum(Integer... nums) {
        System.out.println("java7 calculating condition");//与@

        Integer result = 0;
        for (Integer num : nums) {
            result += num;
        }
        return result;
    }
}

Java8CalculateCondition.java

@CalConditional("java8")
@Component
public class Java8CalculateCondition implements Calculate {
    @Override
    public Integer sum(Integer... num) {
        System.out.println("java8 calculating condition");
        return Stream.of(num).reduce(0, Integer::sum);
    }
}

Learn02AnnotationconfigApplication.class

@SpringBootApplication(scanBasePackages = "com.xmg.learn02annotationconfig.calculate")
public class Learn02AnnotationconfigApplication {

    public static void main(String[] args) {

        System.setProperty("myProfile","java7");
        SpringApplication springApplication = new SpringApplicationBuilder(Learn02AnnotationconfigApplication.class)
                .web(WebApplicationType.NONE)
//              .profiles("java8")
                .build(args);
        ConfigurableApplicationContext context = springApplication.run(args);

        Calculate ca = context.getBean(Calculate.class);
        System.out.println(ca.sum(1, 2, 3, 4, 5));
    }

}

控制台输出:

...
No active profile set, falling back to default profiles: default
...
java7 calculating condition
15

你可能感兴趣的:(条件装配(@Profile方式))