日期:2014-05-19 浏览次数:20642 次
@Repository("userDAO") public class UserDAOImpl implements UserDAO { private HibernateTemplate hibernateTemplate; @Resource//让spring注入进来 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public void add(User u) { hibernateTemplate.save(u); } }
@Repository("logDAO") public class LogDAOImpl implements LogDAO { private HibernateTemplate hibernateTemplate; @Resource//让spring注入进来 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } @Override public void add(Log log) { System.out.println("调用了LogDAO的add方法!"); hibernateTemplate.save(log); throw new RuntimeException("日志打印异常!"); } }
@Service("userService") public class UserServiceImpl implements UserService{ private UserDAO userDAO; private LogDAO logDAO; public UserDAO getUserDAO() { return userDAO; } public LogDAO getLogDAO() { return logDAO; } @Resource public void setLogDAO(LogDAO logDAO) { this.logDAO = logDAO; } @Resource public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } @Transactional public void add(User u){ logDAO.add(new Log("a user saved!")); userDAO.add(u); } }
<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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!--把com.hktk包下的东西交给spring管理 --> <context:component-scan base-package="com.hktk" /> <!-- 加载properties文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源 --> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="o