案例演示
@Conditional作用是按照一定的条件进行判断,满足条件就给容器注册bean,它可以用在带有@Bean注解的方法上,如果给定条件计算结果为true,就会创建bean,否则就会忽略这个bean。
1、实现Condition接口的类
package com.lian.demo.bean;
import lombok.Data;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
@Data
public class Person implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//返回true,则注入bean,否则忽略bean
return true;
}
}
2、@Conditional注解
package com.lian.demo.service;
import com.lian.demo.bean.Person;
import com.lian.demo.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
@Component
public class AutoConfig {
//如果条件为true则创建bean,否则忽略bean
@Conditional(value = Person.class)
//bean别名pi
@Bean(name = "pi")
public User user(){
return new User("dan",3);
}
}
3、测试@Conditional
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConditionDemo {
@Autowired
ApplicationContext applicationContext;
@Test
public void run(){
User user = (User) applicationContext.getBean("pi");
System.out.println("用户姓名"+user.getName()+"年龄"+user.getAge());
}
}
如果注入bean成功,返回结果
用户姓名dan年龄3
如果注入bean失败,返回结果
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'pi' available