条件注解
Profile实际上就是条件注解的一种特殊形式,即条件注解更加灵活,用户可以根据各种不同的条件使用不同的Bean。
条件注解在SpringBoot中使用非常广泛。SpringBoot中提供了许多自动化的配置,例如数据库配置,SpringBoot使用条件注解提前配置好许多常用的类,使用条件注解,在某一个条件满足时,这些配置就会生效
1.创建接口
package com.sxt.service;
public interface ShowCmd {
public String show();
}
2.创建接口的实现类
package com.sxt.service.impl;
import com.sxt.service.ShowCmd;
public class WindowsShowCmd implements ShowCmd {
@Override
public String show() {
System.out.println("windows:dir");
return "dir";
}
}
package com.sxt.service.impl;
import com.sxt.service.ShowCmd;
public class LinuxShowCmd implements ShowCmd {
@Override
public String show() {
System.out.println("linux:ls");
return "ls";
}
}
3.定义条件Condition
package com.sxt.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class WindowsShowCondition implements Condition{
/**
* 匹配条件
* @return
* true 匹配
* false 不匹配
*/
@Override
public boolean matches(ConditionContext cc, AnnotatedTypeMetadata atm) {
String[] profiles = cc.getEnvironment