目标对象:
package cn.itcast.day02;
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");
}
}
通知对象:
package cn.itcast.day02.annotation_test;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;@Aspect
public class MyActive {
@Pointcut("execution(* cn.itcast.day02.*ServiceImpl.*(..))")
public void pc() {}//指定前置通知,并制定切入点
@Before("MyActive.pc()")
public void before() {
System.out.println("前置通知");
}
@AfterReturning("MyActive.pc()")
public void afterReturning() {
System.out.println("后置通知出现异常不会调用");
}
@Around("MyActive.pc()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕通知调用之前");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("环绕通知之后");
return proceed;
}
@AfterThrowing("MyActive.pc()")
public void afterException() {
System.out.println("出现异常");
}
@After("MyActive.pc()")
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.annotation_test.MyActive" ></bean>
<!-- 3.开启使用注解完成织入 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
测试类:
package cn.itcast.day02.annotation_test;
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;import cn.itcast.day02.TargetService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/itcast/day02/annotation_test/applicationContext.xml")
public class Annotation_apoTest {
@Resource(name="targetService")
private TargetService ts;
@Test
public void fun () {
ts.add();
}
}