Spring 的代理服务
在service层接口内容:
public interface IInfoObjectService{
public abstract InfoObject saveInfoObject(InfoObject infoObject) throws InfoObjectException;
public abstract InfoObject findInfoObjectById(Long id) throws InfoObjectException;
public abstract List findAllInfoObjects() throws InfoObjectException;
public abstract void removeInfoObject(Long deleteId) throws InfoObjectException;
public abstract boolean isValidUser(String username, String password);
}
实现service层接口类内容:
public class InfoObjectServiceImpl implements IInfoObjectService {
IInfoObjectDAO infoDAO;
public InfoObject saveInfoObject(InfoObject infoObject) throws InfoObjectException {
InfoObject saveInfo = null;
try{
saveInfo = infoDAO.saveInfoObject(infoObject);
}catch (RuntimeException e) {
throw new InfoObjectException("Could not save InfoObject " + e.toString());}
return saveInfo;
}
public List findAllInfoObjects() throws InfoObjectException {
return infoDAO.getAllInfoObjects();
}
在Spring配置文件配置事物管理:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
设置代理:
<bean id="userDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target"><ref local="dao---注入这里就要给哪个service类做代理,就写哪个类名"/></property>
<property name="transactionAttributes">--通过这个属性定义怎样处理
<props>
<prop key="find*">PROPAGATION_REQUIRED,readOnly,-InfoObjectException</prop>
<prop key="save*">PROPAGATION_REQUIRED,-InfoObjectException</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="is*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
注意:对属性transactionAttributes的说明:
只要在InfoObjectService中所有以find开头的方法则以只读的事务处理机制进行处理。(设为只读型事务,可以使持久层尝试对数据操作进行优化,如对于只读事务Hibernate将不执行flush操作,而某些数据库连接池和JDBC 驱动也对只读型操作进行了特别优化。);
而且包含抛出异常的代码处理机制.
只要在InfoObjectService中所有以is开头的方法则以只读的事务处理机制进行处理。(设为只读型事务,可以使持久层尝试对数据操作进行优化,如对于只读事务Hibernate将不执行flush操作,而某些数据库连接池和JDBC 驱动也对只读型操作进行了特别优化。);
而使用save开头的方法,将会纳入事务管理范围。如果此方法中抛出异常,则Spring将当前事务回滚,如果方法正常结束,则提交事务。
还有使用insert开头的方法,将会纳入事务管理范围。如果此方法中抛出异常,则Spring将当前事务回滚,如果方法正常结束,则提交事务。