項目結構圖以下: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