标签:
1. 默认按类型 by type, 如果想用byname, 使用@Qualifier
2. 如果写在set上, @qualifier需要写在参数上
bean.xml:
默认bytype去找set方法, 注入
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService" > </bean> </beans>
在set方法上加入@AutoWired:
package com.bjsxt.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void init() { System.out.println("init"); } public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } @Autowired public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public void destroy() { System.out.println("destroy"); } }
如果bytype找到2个bean , 参考下面的xml文件,可以在service文件里再加入@Qualifier标识符,
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="u2" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService" > </bean> </beans>
UserService.java:
package com.bjsxt.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void init() { System.out.println("init"); } public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } @Autowired public void setUserDAO(@Qualifier("u") UserDAO userDAO) { this.userDAO = userDAO; } public void destroy() { System.out.println("destroy"); } }
Spring ---annotation (重点)--AutoWired 不常用
标签:
原文地址:http://www.cnblogs.com/wujixing/p/5454204.html