@Qualifier注解和@Resource注解
在传统的MVC实现里面 Spring boot 的controller-service-Impl-Dao-db controller层调用service接口层里面的方法大多使用 @Autowired自动注入注解 实际上调用Impl的具体实现 但是当一个接口的方法,对应多个实现的时候,怎么区分到底注入哪一个呢 答案是@Qualifier注解和@Resource注解
@Qualifier注解的用处:当一个接口有多个实现的时候,为了指名具体调用哪个类的实现
@Resource注解:可以通过 byName命名 和 byType类型的方式注入, 默认先按 byName的方式进行匹配,如果匹配不到,再按 byType的方式进行匹配。 可以为 @Service和@Resource 添加 name 这个属性来区分不同的实现
例如:
@Service
public interface myService{
public int findSomeone();
}
//第一种实现
@Service("myServiceImpl1")
public class myServiceImpl1 implements myService{
@Overide
public int findSomeone() {
//根据身份找
}
}
//第二种实现
@Service("myServiceImpl2")
public class myServiceImpl2 implements myService{
@Override
public int findSomeone() {
//根据名字找
}
}
在controller层,采用 1、@Autowired和@Qualifier(“myServiceImpl1”)结合;或者 2、@Resource(name = “myServiceImpl2”); 两种方式指定要注入的是接口的具体是哪个实现类
@Controller
public class UserController{
@Autowired
@Qualifier("myServiceImpl1")
public myService myservice;
@Resource(name = "myServiceImpl2")
public myService myservice2;
@RequestMapping("/findSomeone")
public User findSomeone(@RequestParam("xx") int xx) {
User user = myservice.findSomeone(xx);
return user;
}
}
