项目结构图以下:java
public interface UserService { public int insert(User user); /** * @Description: 根据id获取user * @param @param id * @param @return 参数 * @return User 返回类型 */ public User getUser(int id); }
@Service(value="userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper usermapper; @Override public User getUser(int id) { return usermapper.selectByPrimaryKey(id); } }
@Service(value="userService2") public class UserServiceImpl2 implements UserService { @Autowired private UserMapper usermapper; @Override public User getUser(int id) { return usermapper.selectByPrimaryKey(id); } }
@Controller @RequestMapping("/user") public class UserController { private static final Logger LOG = Logger.getLogger(UserController.class); @Autowired private UserService userService; @RequestMapping(value = "/user", method = RequestMethod.GET) public String userManager(Model model) { int id = 1; User user = userService.getUser(id); model.addAttribute("user", user); return "user/showUser"; } }
@Autowired private UserService userService2;
@Autowired private UserService userService3;
[ org.springframework.web.servlet.DispatcherServlet ] - [ ERROR ] Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ssm.service.UserService com.ssm.controller.UserController.userService3; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.ssm.service.UserService] is defined: expected single matching bean but found 2: userService,userService2
简要分析:没有找到相应的依赖,可是找到了userService,userService2web
参考连接:Spring@Autowired注解与自动装配 – 金丝燕网spring
@Autowired默认是按照byType进行注入的,可是当byType方式找到了多个符合的bean,又是怎么处理的?Autowired默认先按byType,若是发现找到多个bean,则又按照byName方式比对,若是还有多个,则报出异常。swift
例子:tomcat
@Autowired private Car redCar;
- spring先找类型为Car的bean
- 若是存在且惟一,则OK;
- 若是不惟一,在结果集里,寻找name为redCar的bean。由于bean的name有惟一性,因此,到这里应该能肯定是否存在知足要求的bean了
@Autowired也能够手动指定按照byName方式注入,使用 @Qualifier 标签,以下:app
@Controller @RequestMapping("/user") public class UserController { private static final Logger LOG = Logger.getLogger(UserController.class); @Autowired @Qualifier("userService2" ) private UserService userService3; @RequestMapping(value = "/user", method = RequestMethod.GET) public String userManager(Model model) { int id = 1; User user = userService3.getUser(id); model.addAttribute("user", user); LOG.info(user.toString()); return "user/showUser"; } }
另:@Resource(这个注解属于J2EE的)的标签,默认是按照byName方式注入的ide