UserDao与UserDaoImpl:
public interface UserDao { public void save(); }
public class UserDaoImpl implements UserDao { public void save() { System.out.println("保存用户..."); } }
UserService接口及其实现类UserServiceImpl:
public interface UserService { public void addUser(); }
public class UserServiceImpl implements UserService { private UserDao userDao; private String username; //这里的成员变量不需要setter方法。这是与setter注入不同的地方 public UserServiceImpl(UserDao userDao, String username) { this.userDao = userDao; this.username = username; } public void addUser() { System.out.println(username); userDao.save(); } }
配置:
<bean id="userDao" class="cn.framelife.spring.dao.impl.UserDaoImpl"></bean> <!-- index表示的是构造方法中的第几个参数。从0开始。 --> <bean id="userService" class="cn.framelife.spring.service.impl.UserServiceImpl"> <constructor-arg index="0" ref="userDao"></constructor-arg> <constructor-arg index="1" value="zhangsan"></constructor-arg> </bean>