011_Spring IoC学习笔记beans.xml配置方法,使用构造方法注入

注入的方法有很多,通过beans.xml配置属性注入,用构造函数注入,用注释注入,下面介绍怎么用构造函数注入。
参考上一篇博文: http://jt120.iteye.com/blog/1917970
1、给UserServer添加构造方法
public class UserService {
    private UserDAO userDAO;
    public void add(User user) {
        userDAO.save(user);
    }
    public UserDAO getUserDAO() {
        return userDAO;
    }
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    public UserService(UserDAO userDAO) {
        super();
        this.userDAO = userDAO;
    }
}

2、把beans.xml修改为
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean id="u" class="com.jt.dao.impl.UserDAOImpl">
  </bean>
  <bean id="userService" class="com.jt.service.UserService">
    <constructor-arg>
      <ref bean="u"/>
    </constructor-arg>
  </bean>
</beans>

这样就完成了通过构造方法的注入

你可能感兴趣的:(spring,IOC)