@Conditional注解使用

@Conditional:Spring4.0 介绍了一个新的注解@Conditional,它的逻辑语义可以作为"If…then…else…"来对bean的注册起作用。

  • 作用:根据条件,决定类是否加载到Spring Ioc容器中,在SpringBoot中有大量的运用;
  • 应用场景:在一些需要条件满足才是实例化的类中,使用此注解,根据配置文件的不同,来决定这个bean是否加载至ioc容器中。
  • 依赖:org.springframework.context.annotation

一.Condition接口介绍

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.context.annotation;

import org.springframework.core.type.AnnotatedTypeMetadata;

@FunctionalInterface
public interface Condition {
	// ConditionContext context: spring容器上下文环境,可获取配置文件信息
    boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}

二.使用方法

  1. 自定义一个类,实现Conditional接口, 实现matches方法;
public class LinuxCondition implements Condition {

	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
			// 从配置文件获取系统环境的属性
		  String systemName = context.getEnvironment().getProperty("os.name");
		  if(systemName.contains("Linux")){
			  return true;
		  }
		  return false;
	}
}
  1. 在需要判断条件的bean上,加 @Conditional(LinuxCondition.class) ,即可在满足条件,返回值为 true 的时候加载对应的类;
 @Bean
 @Conditional(LinuxCondition.class)
 public TestBean getTestBean(){
  TestBean testBean = new TestBean();
  return testBean;
 }
  1. 作用在类上;
// 可以配合Spring的容器使用
@RestController
@Conditional({LinuxCondition.class})
public class AcsController {
// 如果配合@RestController、@Component等注解使用,当满足条件时,Spring会创建bean;
}

// 可以配合@Configuration注解使用
@Configuration
@Conditional({LinuxCondition.class})
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}
  1. 多个条件作用在类上,满足全部条件才会初始化bean;
// 定义条件-01
public class WindowsCondition implements Condition {

	 @Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		    
		   String systemName = context.getEnvironment().getProperty("os.name");
		   if(systemName.contains("Windows")){
			   return true;
		   }
		return false;
	}

}

// 定义条件-02
public class OsxCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String property = context.getEnvironment().getProperty("os.name");
        if(property.equals("Mac OS X")){
            return true;
        }
        return false;
    }
}

@RestController
@Conditional(value = {OsxCondition.class,TestCondition.class})
public class AcsController {
// 条件全部满足才会初始化
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值