springboot @Qualifier,@Primary使用

场景:当你编写一个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");
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值