0
点赞
收藏
分享

微信扫一扫

005---@Conditional条件判断注解

写心之所想 2022-03-10 阅读 86


@Conditional注解的作用是条件判断注解,特点是可以给方法注解,也可以给整个类注解,表示满足条件才可以执行

使用示例:

下面的代码是其中一个案例: 编写条件类DemoCondition

注释部分是条件判断的示例,判断操作系统是否为Linux

package config;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class DemoCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//获取ioc容器使用的beanFactory
ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
//获取类加载器
ClassLoader classLoader = conditionContext.getClassLoader();
//获取当前环境(java运行环境所在的环境)
Environment environment = conditionContext.getEnvironment();//
//获取定义bean的注册类
BeanDefinitionRegistry registry = conditionContext.getRegistry();
//获取资源加载器
ResourceLoader resourceLoader = conditionContext.getResourceLoader();
/*
String property = environment.getProperty("os.name");
if (property.contains("Linux")){
System.out.println("输出信息:==>"+property);
return true;
}
*/
//默认返回false,前面通过获取到的信息进行if条件判断,符合则return true
return false;
}
}

使用方法:给想要判断的方法 或者 类加上条件注解@Conditional

如下:spring配置类

package config;

import bean.HelloWorld;
import org.springframework.context.annotation.*;


@Configuration
public class Config {

// @Scope("prototype")
@Conditional({DemoCondition.class})
@Bean("hello")
public HelloWorld hello() {
System.out.println("bean加入ioc容器");
return new HelloWorld();
}
}

测试类:运行测试案例前将前面的条件类注释去掉

package config;

import bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


import static org.junit.Assert.*;

public class ConfigTest {

@Test
public void test1(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
HelloWorld hello = (HelloWorld) applicationContext.getBean("hello");
}
}

运行过程:如果不去掉注释可能会报错,原因是返回了false,条件不成立自然就不会加入ioc容器。如果用的是Windows则将Linux改成Windows


举报

相关推荐

0 条评论