Spring Condition 注解

Spring Condition注解的主要作用是根据条件给容器注入bean,简称条件注解。它是spring 4.0引入的新特性

@Component
public class Cat {
}


@Component
@Conditional(Match.class)
public class Dog {
}

public class Match implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return false; } } public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext("com.edu.condition"); String[] beanNames = annotationConfigApplicationContext.getBeanDefinitionNames(); for(String name:beanNames){ System.out.println(name); } } }

Match 实现了Condition,重写 matches方法,当该方法返回true的时候,表示条件满足。

从参数context里面可以获取

1.context.getEnvironment() 环境信息   例如

String osName = context.getEnvironment().getProperty("os.name");  获取操作系统名称

2.context.getRegistry()  注册的bean

3.context.getResourceLoader() 加载的资源

4.context.getBeanFactory()   beanFactory

猜你喜欢

转载自www.cnblogs.com/chenzhubing/p/11199110.html