1 导包
2 将 Service 对象以及 Dao 对象配置到 spring 容器
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "> <!--注册dao层对象到容器中 --> <bean name="userDao" class="www.test.dao.impl.UserDaoImpl"></bean> <bean name="linkManDao" class="www.test.dao.impl.LinkManDaoImpl"></bean> <bean name="customerDao" class="www.test.dao.impl.CustomerDaoImpl"></bean> <!--注册service层对象到容器中 --> <bean name="userService" class="www.test.service.impl.UserServiceImpl"> <property name="ud" ref="userDao"></property> </bean> <bean name="linkManService" class="www.test.service.impl.LinkManServiceImpl"> <property name="cd" ref="customerDao"></property> <property name="lmd" ref="linkManDao"></property> </bean> <bean name="customerService" class="www.test.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"></property> </bean> </beans>
注意对象中需要有对应的属性才能注入。
package www.test.service.impl; import www.test.dao.CustomerDao; import www.test.dao.LinkManDao; import www.test.dao.impl.CustomerDaoImpl; import www.test.dao.impl.LinkManDaoImpl; import www.test.domain.Customer; import www.test.domain.LinkMan; import www.test.service.LinkManService; import www.test.utils.HibernateUtils; public class LinkManServiceImpl implements LinkManService { private CustomerDao cd; private LinkManDao lmd; public void save(LinkMan lm) { //打开事务 HibernateUtils.getCurrentSession().beginTransaction(); try { //1 根据客户id获得客户对象 Long cust_id = lm.getCust_id(); Customer c = cd.getById(cust_id); //2 将客户放入LinkMan中表达关系 lm.setCustomer(c); //3 保存LinkMan lmd.save(lm); } catch (Exception e) { e.printStackTrace(); //回滚事务 HibernateUtils.getCurrentSession().getTransaction().rollback(); } //提交事务 HibernateUtils.getCurrentSession().getTransaction().commit(); } public CustomerDao getCd() { return cd; } public void setCd(CustomerDao cd) { this.cd = cd; } public LinkManDao getLmd() { return lmd; } public void setLmd(LinkManDao lmd) { this.lmd = lmd; } }
3 web.xml配置容器随项目的启动而启动
<!-- 可以让spring容器随项目的启动而创建,随项目的关闭而销毁 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定加载spring配置文件的位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
4 在 Action 中获得容器中的对象
//============================================================= //获得spring容器=>从Application域获得即可 //1 获得servletContext对象 ServletContext sc = ServletActionContext.getServletContext(); //2.从servletContext中获得ApplicationContext容器 WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc); //3.从容器中获得CustomerService CustomerService cs = (CustomerService) ac.getBean("customerService"); //============================================================