2016-11-27 141 views

回答

7

您可以使用@Qualifier和@Autowired。逸岸春天会问你明确选择,如果不明确的bean类型中发现的豆,在这种情况下,你应该提供资格

例如在以下情况下,必须提供一个限定符

@Component 
@Qualifier("staff") 
public Staff implements Person {} 

@Component 
@Qualifier("employee") 
public Manager implements Person {} 


@Component 
public Payroll { 

    private Person person; 

    @Autowired 
    public Payroll(@Qualifier("employee") Person person){ 
      this.person = person; 
    } 

} 
1

的@Qualifier注解用于解决自动装配冲突,当有多个相同类型的bean时。

@Qualifier注释可用于任何用@Component注解的类或用@Bean注释的方法。此注释也可以应用于构造函数参数或方法参数。

例如: -

public interface Vehicle { 
    public void start(); 
    public void stop(); 
} 

有两种豆,汽车和自行车实现车辆接口使用@Autowired与@Qualifier注解中VehicleService

@Component(value="car") 
public class Car implements Vehicle { 

    @Override 
    public void start() { 
      System.out.println("Car started"); 
    } 

    @Override 
    public void stop() { 
      System.out.println("Car stopped"); 
    } 

} 

@Component(value="bike") 
public class Bike implements Vehicle { 

    @Override 
    public void start() { 
      System.out.println("Bike started"); 
    } 

    @Override 
    public void stop() { 
      System.out.println("Bike stopped"); 
    } 

} 

注浆自行车豆。如果你没有使用@Qualifier,它会抛出NoUniqueBeanDefinitionException

@Component 
public class VehicleService { 

    @Autowired 
    @Qualifier("bike") 
    private Vehicle vehicle; 

    public void service() { 
     vehicle.start(); 
     vehicle.stop(); 
    } 
}