谈谈Java CDI 里面的Qualifier

如果只是读官方的文档,关于这个Qualifier的说明比较简单。

这句话读了好几遍还是没看明白表达的意思: You can use qualifiers to provide various implementations of a particular bean type.

又读了一些别的文章,总算看明白了,翻译成中文就是这个qualifier用来给同一个bean的不同实现类。

比如你有一个Vehicel类或者interface,你需要把这个类或者interface分别实现成Car,Bus和Van,这个时候可以用qualifier把这些实现类给区别开。

首先写三个qualifier

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface CarQualifier{}
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface BusQualifier{}
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface VanQualifier{}

 

上面这些都是固定模式,现在写这个父类

public interface Vehicle{
    String getName();
}

在继承的时候可以这么写

@CarQualifier
public class Car implements Vehicle {

 @Override
    public String getName() {
        return "Hi, this is car!";
    }
}

我就不再重复写bus和van的实现类了,这里只是写一下怎么做injection

1. Injection Through Fields

public class Example {
 
    @Inject
    @CarQualifier
    private Vehicle car;
 
    @Inject
    @BusQualifier
    private Vehicle bus;
 
    @Inject
    @VanQualifier
    private Vehicle van;
 
    ...
}

2.Injection Through Setter Methods

public class Example {
 
    private Vehicle car;
    private Vehicle bus;
    private Vehicle van;
 
    @Inject
    public void setCar(@Bmw Vehicle car) {
        this.car = car;
    }
 
    @Inject
    public void setBus(@Honda Vehicle bus) {
        this.bus = bus;
    }
 
    @Inject
    public void setVan(@Ford Vehicle van) {
        this.van= van;
    }
   
   ...
}

 

3.Injection Through Constructor

public class VehicleImp {
 
    private Vehicle car;
    private Vehicle bus;
    private Vehicle van;
 
    @Inject
    public AutoServiceCallerImp(@Bmw Vehicle car,
                             @Honda Vehicle bus,
                             @Ford Vehicle van) {
 
        this.car= car;
        this.bus= bus;
        this.van= van;
    }

    ...
}

 

献丑了。

 

 

 

 

 

 

你可能感兴趣的:(Java杂谈)