原理:首先,要得到一个正确的SessionFactory,这里跳过~,然后声明一个spring aop,
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-lazy-init="false">
<bean id="loginTran" class="org.vean.aop.TranAop">
<property name="sf" ref="sessionFactory"></property>
</bean>
<aop:config>
<aop:pointcut expression="execution(* org.vean.services.LogLoginService.*(..))"
id="txcut" />
<!-- <aop:advisor advice-ref="loginTran" pointcut-ref="txcut" />-->
<aop:aspect ref="loginTran">
<aop:around method="LogLoginServiceTran" pointcut-ref="txcut"/>
</aop:aspect>
</aop:config>
</beans>
我们先用传统的aop方式配置切点和切面:
这是一个对org.vean.services.LogLoginService类中的所有的方法aop拦截配置,也就是说,我要对LogLoginService中的所有方法植入事务,声明切面并应用spring管理的id为“LoginTran”的类,使用环绕通知,引用上面的额顶级切点,环绕通知调用LoginTan类的LogLoginServiceTran方法,下面为TranAop类:
package org.vean.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.hibernate.SessionFactory;
public class TranAop implements MethodInterceptor{
private SessionFactory sf;
public SessionFactory getSf() {
return sf;
}
public void setSf(SessionFactory sf) {
this.sf = sf;
}
public Object LogLoginServiceTran(ProceedingJoinPoint jsp){
this.getSf().getCurrentSession().getTransaction().begin();
Object obj=null;
try {
obj=jsp.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.getSf().getCurrentSession().getTransaction().rollback();
}
this.getSf().getCurrentSession().getTransaction().commit();
return obj;
}
@Override
public Object invoke(MethodInvocation arg0) {
// TODO Auto-generated method stub
this.sf.getCurrentSession().getTransaction().begin();
Object obj=null;
try {
obj=arg0.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.sf.getCurrentSession().getTransaction().commit();
}
return obj;
}
}
这就完成了对切入点拦截的方法植入了事务。
因为实现了
MethodInterceptor这个类,所以我们可以在xml不需要切面的配置了,下面的配置就Ok:
<aop:advisor advice-ref="loginTran" pointcut-ref="txcut" />