Spring框架中@Primary注解的作用

@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");
    }
}

控制台输出结果:
在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值