第一步:目标类(Service和Dao)
//dao层
package it.heima.aspectj;
public class AccoutDao {
public void out(String name,Double monney){
System.out.println(name+"成功转出"+monney);
}
public void in (String name,Double monney){
System.out.println(name+"成功转入"+monney);
}
}
//service层
package it.heima.aspectj;
public class AccountService {
private AccoutDao accoutDao;
public void setAccoutDao(AccoutDao accoutDao){
this.accoutDao=accoutDao;
}
public void transfer(String name1,String name2,Double monney){
accoutDao.out(name1,monney);
int num=1/0;//模拟断电
accoutDao.in(name2,monney);
}
}
第二步:增强类编码
package it.heima.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAspect {
public Object around(ProceedingJoinPoint proceedingJoinPoint){
Object returnResult=null;
try {
System.out.println("开启事务..");
returnResult=proceedingJoinPoint.proceed();
System.out.println("事务正常,提交事务");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("事务异常,回滚事务");
}finally {
System.out.println("释放资源");
}
return returnResult;
}
}
第三步:配置文件applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置Dao层-->
<bean id="accoutDao" class="it.heima.aspectj.AccoutDao"></bean>
<!--配置service层-->
<bean id="accountService" class="it.heima.aspectj.AccountService">
<property name="accoutDao" ref="accoutDao"/>
</bean>
<!--配置增强类-->
<bean id="myAspect" class="it.heima.aspectj.MyAspect"></bean>
<!--让增强类和普通类产生关系-->
//默认是直接用cglib的,此处可以让他从JDK动态代理开始,如果JDK动态代理解决不了再用cglib解决
<aop:config proxy-target-class="false">
//引入切面(即增强类)
<aop:aspect ref="myAspect">
//引入切点(即所有Service结尾的around方法)
<aop:around method="around" pointcut="bean(*Service)"/>
</aop:aspect>
</aop:config>
</beans>
第四步:测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountServiceTest {
@Value("#{accountService}")
private AccountService accountService;
@Test
public void test(){
accountService.transfer("aaa","bbb",100.0);
}
}