Spring Framework条件装配笔记

基于配置方式实现

实例:

定义一个基础服务的接口

/**
 * 计算服务
 */
public interface CalculateService {

    /**
     * 多个整数求和
     * @param value  多个整数
     * @return  累加和
     */
    Integer sum(Integer... value);
}

定义相关的条件实现类

/**
 * Java 7 for循环实现{@link CalculateService}
 */
@Profile("Java7") // 条件装配
@Service
public class Java7CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... value) {
        System.out.println("Java 7 for循环实现");
        int sum = 0;
        for (int i = 0; i < value.length; i++) {
            sum += value[i]; // 通过下标来获取
        }
        return sum;
    }
}

/**
 * Java 8 for循环实现{@link CalculateService}
 */
@Profile("Java8") // 条件装配
@Service
public class Java8CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... value) {
        System.out.println("Java 8 for循环实现");
        int sum = Stream.of(value).reduce(0, Integer::sum);
        return sum;
    }
}

启动容器

/**
 * {@link CalculateService} 引导类
 */
@SpringBootApplication(scanBasePackages = "com.SpringBootStudy.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 serviceBootstrap = context.getBean(CalculateService.class);
        System.out.println("calculateService.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) = " + serviceBootstrap.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        // 关闭上下文
        context.close();
    }
}

基于编程的方式实现

范例:

自定义注解

/**
 * Java 系统属性条件判断
 * System下的getProperty
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {

    /**
     * Java 系统属性的名称
     * @return
     */
    String name();

    /**
     * 系统属性匹配值
     * @return
     */
    String value();
}

实现Spring Framework中的Condition【Spring Boot其实也是实现的Spring Framework中的Condition】

package org.springframework.context.annotation;

import org.springframework.core.type.AnnotatedTypeMetadata;

@FunctionalInterface
public interface Condition {
    boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
/**
 * 系统属性的条件判断
 * 在springboot中的Profile是使用的Spring Framework中的Condition
 */
public class OnSystemPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        // 取得在用这个注解的参数和值【反射】
        Map<String, Object> attribute =  annotatedTypeMetadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        String propertyName = String.valueOf(attribute.get("name"));
        String propertyValue = String.valueOf(attribute.get("value"));

        // 取得系统的PropertyValue
        String javaPropertyValue = System.getProperty(propertyName);
        // 比较
        return propertyValue.equals(javaPropertyValue);
    }
}

启动容器

/**
 * 系统条件引导类
 */
public class ConditionalOnSystemPropertyBootstrap {

    @Bean // 交给Spring 容器初始化
    // 条件装配 要与系统的System.getProperty(propertyName)匹配才初始化
    @ConditionalOnSystemProperty(name="user.name", value = "Administrator")
    public String hello(){
        return "hello";
    }


    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        // 通过名称获取到hello Bean
        String hello = context.getBean("hello", String.class);
        System.out.println("hello Bean :" + hello);
        context.close();
    }
}


/**
 * 2021-03-29 21:32:24.613  INFO 52856 --- [           main] d.b.ConditionalOnSystemPropertyBootstrap : Starting ConditionalOnSystemPropertyBootstrap using Java 1.8.0_261 on MicroWin10-1647 with PID 52856 (C:\Users\Administrator\Desktop\workspace\技术栈\dive-in-spring-boot\target\classes started by Administrator in C:\Users\Administrator\Desktop\workspace\技术栈\dive-in-spring-boot)
 * 2021-03-29 21:32:24.615  INFO 52856 --- [           main] d.b.ConditionalOnSystemPropertyBootstrap : No active profile set, falling back to default profiles: default
 * 2021-03-29 21:32:24.752  INFO 52856 --- [           main] d.b.ConditionalOnSystemPropertyBootstrap : Started ConditionalOnSystemPropertyBootstrap in 0.464 seconds (JVM running for 0.865)
 * hello Bean :hello
 */

From 《慕课网Spring Boot2.0 小马哥视频》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值