@Conditional的用法
package com.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* @auto dh
* @create 2020-04-25-15:11
*/
public class Condition001 implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
// context 代表Ioc容器 context.getBeanFactory 从Ioc容器里获取容器工厂
// 调用该容器工厂,判断是否包含该bean名为animal
if(context.getBeanFactory().containsBean("animal")){
return true;
}
return false;
}
}
package com.configuration;
import com.bean.Animal;
import com.bean.Person;
import com.condition.Condition001;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* @auto dh
* @create 2020-04-25-15:15
*/
@Configuration
public class ConditionTest001 {
// @Bean
public Animal animal() {
return new Animal();
}
@Bean
// 如果Condition001.class返回true,则加载该bean,
// 否则不加载该bean
@Conditional(Condition001.class)
public Person person() {
return new Person();
}
}