目标对象:
public class TargetServiceImpl implements TargetService {
public void add() {
System.out.println("add");
}
public void update() {
System.out.println("update");
}
public void delete() {
System.out.println("delete");
}
public void find() {
System.out.println("find");
}
通知对象:
public class MyActive {
public void before() {
System.out.println("前置通知");
}
public void afterReturning() {
System.out.println("后置通知出现异常不会调用");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕通知调用之前");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("环绕通知之后");
return proceed;
}
public void afterException() {
System.out.println("出现异常");
}
public void after() {
System.out.println("后置通知出现异常也会通知");
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "><!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
<bean name="targetService" class="cn.itcast.day02.TargetServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
<bean name="myAdvice" class="cn.itcast.day02.MyActive" ></bean>
<!-- 3.配置将通知织入目标对象 -->
<aop:config>
<!-- 配置切入点
public void cn.itcast.service.UserServiceImpl.save()
void cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.*()
* cn.itcast.service.*ServiceImpl.*(..)
* cn.itcast.service..*ServiceImpl.*(..)
* cn.itcast.day02.*ServiceImpl.*(..)
-->
<aop:pointcut expression="execution(* cn.itcast.day02.*ServiceImpl.*(..))" id="pc"/>
<aop:aspect ref="myAdvice" >
<!-- 指定名为before方法作为前置通知 -->
<aop:before method="before" pointcut-ref="pc" />
<!-- 后置 -->
<aop:after-returning method="afterReturning" pointcut-ref="pc" />
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="pc" />
<!-- 异常拦截通知 -->
<aop:after-throwing method="afterException" pointcut-ref="pc"/>
<!-- 后置 -->
<aop:after method="after" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
</beans>
测试类:
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/itcast/day02/applicationContext.xml")
public class aopTest {
@Resource(name="targetService")
private TargetService ts;
@Test
public void fun () {
ts.add();
}
}