注解概括
Conditional注解
当满足一定条件是才向Spring容器中注册Bean。
该注解可以注释在配置类或者方法上,向其中传入实现了Condition接口的类变量。如果配置在方法上,则满足条件当前Bean方法生效。如果配置在类上,则满足条件当前类中的所有Bean方法全部生效。
Since Spring4.0
代码演示
先创建一个Bean对象
Subject.java
package cc.fireflyhut.selfstudy.bean;
public class Subject {
public Subject() {}
public Subject(String name, String element) {
this.name = name;
this.element = element;
}
private String name;
private String element;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
}
创建两个实现Condition接口的类
ConditionEvenImpl.java
package cc.fireflyhut.selfstudy.bean.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.util.Date;
public class ConditionEvenImpl implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Date now = new Date();
int num = now.getSeconds();
if (num % 2 == 0) {
return true;
}
return false;
}
}
package cc.fireflyhut.selfstudy.bean.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.util.Date;
public class ConditionOddImpl implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Date now = new Date();
int num = now.getSeconds();
if (num % 2 != 0) {
return true;
}
return false;
}
}
再创建一个配置类
BeanConfig.java
package cc.fireflyhut.selfstudy.bean;
import cc.fireflyhut.selfstudy.bean.condition.ConditionEvenImpl;
import cc.fireflyhut.selfstudy.bean.condition.ConditionOddImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
public class BeanConfig {
@Conditional(ConditionOddImpl.class)
@Bean
public Subject odd() {
return new Subject("一只小对象", "奇数哦~");
}
@Conditional(ConditionEvenImpl.class)
@Bean
public Subject even() {
return new Subject("一只大对象", "偶数!");
}
}
开始在测试类中测试
package cc.fireflyhut.selfstudy.bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BeanTest {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
@Test
public void test() {
String[] beanName = applicationContext.getBeanNamesForType(Subject.class);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
for (String name : beanName) {
System.out.println(name);
}
}
}
在秒数为奇数的时候可以看到名字为odd的bean被注册,秒数为偶数的时候名字为even的bean被注册到容器中。