springboot @Qualifier,@Primary使用

本文介绍了在Spring中处理多个相同接口实现类的情况,通过@Qualifier注解精确注入所需服务,并展示了如何使用@Primary注解设置默认实现,简化代码中的注入过程。在测试类中,通过@Qualifier指定所需的服务实例进行测试,而在频繁使用的接口上,使用@Primary标记一个默认实现,以减少重复的注解使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景:当你编写一个service接口时,有多个不同的实现类,那么你该如何取到你需要的方法呢?
解决方法:使用@Qualifier注解
1.service代码
/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/15
 */

public interface TestService {
    void print();
}

2.service实现类1
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/15
 */
@Service("testServiceImpl1")
//service处如果不取别名,则默认为类名,首字母小写
public class TestServiceImpl1 implements TestService {
    @Override
    public void print() {
        System.out.println("我是1");
    }
}

3.service实现类2
/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/15
 */
@Service("testServiceImpl2")
public class TestServiceImpl2 implements TestService {
    @Override
    public void print() {
        System.out.println("我是2");
    }
}
4.测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/15
 */
@SpringBootTest
@RunWith(SpringRunner.class)
//这两个注解表示测试启动spring容器,可以使用springboot相关注解,否则会出现空指针异常
public class Testdaf {
    @Autowired
    //注意,此处对应@service后面去的别名,如果@Service后面没有取别名,则默认别名为类名,首字母小写
    @Qualifier("testServiceImpl1")
    TestService testService;

   @Test
     public  void testZhujie(){
        testService.print();
     }
}

案例升级 :

你使用@Autowired还要跟上@Qualifier,如果很多个地方用到同一个接口,而每次用这个接口都要使用@Qualifier,是不是很麻烦,那么你可以在调用接口的地方加上@pramary

 @Autowired
    //注意,此处对应@service后面去的别名,如果@Service后面没有取别名,则默认别名为类名,首字母小写
    @Qualifier("testServiceImpl1")
    TestService testService;
使用@Primary:在你频繁使用接口的类上加上@Primary
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author:ay
 * @Date:2020/10/15
 */
@Service("testServiceImpl2")
@Primary
public class TestServiceImpl2 implements TestService {
    @Override
    public void print() {
        System.out.println("我是2");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值