综合案例
1.创建项目
2.创建dao层
public interface IUserDao { public String add(); }
public class UserDaoImpl implements IUserDao { @Override public String add() { // TODO Auto-generated method stub return "hello ... "; } }
3.创建service层
public interface IUserService { public String add(); }
public class UserServiceImpl implements IUserService { private IUserDao dao; // 设值注入 必须的方法 public void setDao(IUserDao dao) { this.dao = dao; } @Override public String add() { return dao.add(); } }
4.创建controller层
/** * 控制层 * @author dpb * */ public class UserController { private IUserService service; // 设值注入必须的方法 public void setService(IUserService service) { this.service = service; } public String add(){ return service.add(); } }
5.配置文件
<!-- 配置 dao --> <bean class="com.sxt.dao.impl.UserDaoImpl" id="userDaoImpl"/> <!-- 配置 service --> <bean class="com.sxt.service.impl.UserServiceImpl" id="userServiceImpl"> <!-- 设值注入 dao对象 --> <property name="dao" ref="userDaoImpl"></property> </bean> <!-- 配置controller --> <bean class="com.sxt.controller.UserController"> <!-- 设值注入service对象 --> <property name="service" ref="userServiceImpl"></property> </bean>
测试
@Test public void test2() { // 获取ApplicationContext对象 加载配置文件 反射+xml解析 ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml"); UserController bean = ac.getBean(UserController.class); System.out.println(bean.add()); }