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