@Autowired & @Qualifier
@Autowired 主要用来自动装配,在容器中找到我们需要的Bean
@Qualifer 则是当一个接口有多个实现类的时候,可以作为条件更精确的找到我们需要的Bean
js
public interface PaymentService{
void processPayment();
}
@Component("creditCardPaymentService")
public class CreditCardPaymentService implements PaymentService{
@Override
public void processPayment(){
System.out.println("Card")
}
}
public class PaypalPaymentService implements PyamentService{
@Override
public void processPayment(){
System.out.println("Paypal")
}
}
#使用,如果前面不区分,这里会报错,不知道使用哪一个
@Component
public class Shpping{
@Autowired
@Qualifer("creditCardPaymentService")
private PaymentService paymentService
}
@Autowired的高级使用
当@Autowired注解一个方法,并且该方法的参数是一个接口的时候,Spring会自动收集这个接口的所有实现类
1.Spring的依赖注入,容器会扫描所有已注册的Bean,寻找和目标匹配的实例
2.当Spring遇到Collection
,List
, Set
或者数组类型的依赖时,会自动收集所有匹配该泛型类型的Bean
3.当@Autowired用在方法上,Spring会在创建Bean后调用改方法,自动传入所有匹配的参数
js
public interface PaymentProcessor{
void process()
}
@Component
public class CreditCardProcessor implements PaymentProcessor{
@Override
pubic void process(){
}
}
@Component
public class PaypalProcessor implements PaymentProcessor{
@Override
public void processor(){
}
}
#使用@Autowired方法注入
@Service
public class PaymentService{
private List<PaymentProcessor> processors;
public void setProcessors(List<PaymentProcessor> processors){
this.processors = processors;
}
//xxxxxxxxx
}
@Conditional
@Conditional是Spring Framework中实现条件化配置的核心方式。它允许根据特定的条件来决定是否注册一个Bean.
自定义Conditional
js
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.env.Environment;
public class MyCustomCondition implements Condition{
@Override
public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata){
//从环境变量获取
Environment env = context.getEnvironment();
return "true".equals(env.getProperty("myapp.feature.enabled"))
}
}
可以用在@Bean
方法上,@Component
类上或者@Configuration
类上
js
@Configuration
public class AppConfig{
@Bean
@Conditional(MyCustomCondition.class)
public MyService(){
return new MyService();
}
}
SpringBoot 衍生注解
1.@ConditionalOnProperty 根据配置决定是否生效
2.@ConditionalOnBean 根据容器中是否存在Bean而生效
3.@ConditionalOnWebApplication 当前应用是否事Web应用而生效
js
@Service
@ConditionalOnProperty(
value = "myapp.feature.enabled", //属性
havingValue = "true", //属性值
matchIfMissing = false //如果属性缺失,是否匹配,false表示缺失不匹配
)
public class MyServiceImpl implements MyService{
// 只有当myapp.feature.enable=true
}