@Conditional使用
@Conditional注解
此注解使用可以根据不同的条件来判断是否注册对象,可以灵活改变bean的注册
例如:
我们开发一个文件保存系统,我有个顶层借口,结构如下:
public interface FileService<T> {
String saveFile(T o) throws Exception; //保存文件,返回文件key
T readFile(String filekey) throws Exception;//根据文件key读取文件
void deleteFile(String filekey) throws Exception;//删除文件
}
我们可以选择本地保存或者使用ftp保存,代码如下:
/**
* 本地保存
*/
@Service
public class LocalFileServiceImpl implements FileService<byte[]> {
@Override
public String saveFile(byte[] byteArrs) throws Exception { //保存文件到本地 }
@Override
public byte[] readFile(String filekey) throws Exception { //读取本地文件 }
@Override
public void deleteFile(String filekey) throws Exception { //删除本地文件 }
}
/**
* ftp保存
*/
@Service
public class FtpFileServiceImpl implements FileService<byte[]> {
@Override
public String saveFile(byte[] byteArrs) throws Exception { //保存文件到ftp服务 }
@Override
public byte[] readFile(String filekey) throws Exception { //读取ftp服务文件 }
@Override
public void deleteFile(String filekey) throws Exception { //删除ftp服务文件 }
}
到这里,我们就有了两个服务来处理本地文件和ftp文件里,但是我们怎么控制什么时候使用本地服务,什么时候使用ftp服务呢?
这是就要使用到==@Conditional==注解
我们先来看看这个注解,他里边有一个参数:
/**
All Conditions that must matches in order for the component to be registered.
*/
Class<? extends Condition>[] value();
参数是接受一个一个Condition的class数组,注释是指所有的Condition全部匹配,当前bean才会被注册
所以我们需要先写一个Conditions来进行是否注册的判断
public class LocalFileCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String file_model= environment.getProperty("配置文件中的文件保存方式");
return "local".equals(file_model); //本地方式会注册
}
}
public class FtpFileCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String file_model= environment.getProperty("配置文件中的文件保存方式");
return "ftp".equals(file_model); //ftp方式会注册
}
}
ConditionContext 里还可以获取其他的bean,资源,可根据需要获取:
// 获取Bean定义
BeanDefinitionRegistry getRegistry();
// 获取Bean工程,因此就可以获取容器中的所有bean
ConfigurableListableBeanFactory getBeanFactory();
// environment 持有所有的配置信息
Environment getEnvironment();
// 资源信息
ResourceLoader getResourceLoader();
// 类加载信息
ClassLoader getClassLoader();
接下来我们的LocalFileServiceImpl,FtpFileServiceImpl上加上这个注解
@Conditional(LocalFileCondition.class)
@Service
public class LocalFileServiceImpl implements FileService<byte[]>
@Conditional(FtpFileCondition.class)
@Service
public class FtpFileServiceImpl implements FileService<byte[]>
这样就可以根据配置文件来修改具体注册的bean了
其实还有种更简单的方法实现,就是使用@ConditionalOnProperty
@ConditionalOnProperty(value = "配置文件中的文件保存方式",havingValue = "local")
直接把他加在LocalFileServiceImpl上也能实现此效果
除此之外还有
多种多样,大家可以自己研究下