@Primary注解
@Primary的作用就是当一个接口存在多个实现类时,我们就可以通过@Primary注解来指明哪个实现类作为首选进行自动装配注入。
如果不加@Primary注解,接口ICarService存在两个不同的实现类,我们启动项目,由于存在两个ICarService的实现类,Spring不知道为我们注入哪一个,就会报如下的异常。
***************************
APPLICATION FAILED TO START
***************************
Description:
Field carService in com.lbb.controller.CarController required a single bean, but 2 were found:
- audiCarService: defined in file [D:\ideaprojects\test\target\classes\com\lbb\service\impl\AudiCarService.class]
- BMWCarService: defined in file [D:\ideaprojects\test\target\classes\com\lbb\service\impl\BMWCarService.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
Process finished with exit code 1
如果在某一个实现类中添加@Primary注解,通过控制台打印,说明Spring为我们自动注入的是经过@Primary注解修饰的AudiCarService。
package com.lbb.service.impl;
import com.lbb.service.ICarService;
import org.springframework.stereotype.Service;
@Service
public class BMWCarService implements ICarService {
@Override
public void drive() {
System.out.println("bmw drive");
}
}
package com.lbb.service.impl;
import com.lbb.service.ICarService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
@Primary
@Service
public class AudiCarService implements ICarService {
@Override
public void drive() {
System.out.println("audi drive");
}
}
控制台输出结果: