Spring @Qualifier和@Primary注解使用
- @Autowired是根据类型进行自动装配的。如果当Spring上下文中存在多个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。
- 补充:当一个service有多个impl实现类的时候,使用@Autowired注解来注入service的时候可能会报错,因为有多个impl导致Spring不知道使用哪个了。
public interface TestService {
JSONObject selectEmp();
}
@Service("service2")
public class Test1ServiceImpl implements TestService{
@Override
public JSONObject selectEmp() {
System.out.println("selectEmp");
return null;
}
}
@Service("service1")
public class TestServiceImpl implements TestService{
@Override
public JSONObject selectEmp() {
System.out.println("selectEmp");
return null;
}
}
@RestController
@RequestMapping("/Select")
public class SelectController {
@Qualifier("service1")
@Autowired
public TestService testService;
}
- 使用 @Autowired + @Qualifier 来指定使用哪个具体的Impl。
- 如果想指定一个默认的Service时,那么我们可以使用@Primary注解。
public interface TestService {
JSONObject selectEmp();
}
@Service("service2")
public class Test1ServiceImpl implements TestService{
@Override
public JSONObject selectEmp() {
System.out.println("selectEmp");
return null;
}
}
@Service("service1")
@Primary
public class TestServiceImpl implements TestService{
@Override
public JSONObject selectEmp() {
System.out.println("selectEmp");
return null;
}
}
- 这样在使用@Autowired进行注入的时候 可以使用默认的Impl。