首先,最重要的, @Autowired的就是用来来消除 set ,get方法.
有些介绍,如著名的马士兵,说要在set方法上进行注入.我当时就看不明白了,既然只取消了一个GET,这个@Autowired还有什么屁用.不是瞎折腾么.还要用@Qualifier来帮忙指定BEAN.
如下:
// @Autowired
// public void setUserDAO(@Qualifier("userDAOImpl") UserDAO userDAO) {
// this.userDAO = userDAO;
// }
后来自己试了一下,在SPRING2.5和3.0下,都不用这样.
直接使用
Autowired 即可
@Autowired
private UserDAO userDAO;
也不需要在applicationContext.xml中加入:
<!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
贴出我的SPRING配置文件
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="userDAOImpl" class="com.bjsxt.dao.impl.UserDAOImpl">
</bean>
<bean id="userService" class="com.bjsxt.service.UserService" >
</bean>
</beans>
public class UserService { @Autowired private UserDAO userDAO; public void add(User user) { userDAO.save(user); } // @Autowired // public void setUserDAO(@Qualifier("userDAOImpl") UserDAO userDAO) { // this.userDAO = userDAO; // } }
public class UserServiceTest { @Test public void testAdd() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); UserService service = (UserService)ctx.getBean("userService"); service.add(new User()); } }