Spring 使用 AspectJ 进行 AOP 的开发
1)引入相关的jar包
- spring 的传统 AOP 的开发的包: spring-aop-4.2.4.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar - aspectJ 的开发包: com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aspects-4.2.4.RELEASE.jar
2)引入Spring的配置文件
引入 AOP 约束:
<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">
</beans>
3)编写目标类
public class ProductDao {
public void save() {
System.out.println("保存商品...");
}
public void update() {
System.out.println("修改商品...");
}
public void delete() {
System.out.println("删除商品...");
}
public void find() {
System.out.println("查询商品...");
}
}
4)配置目标类
<bean id="productDao" class="cn.itcast.spring.demo4.ProductDao"></bean>
5)开启aop注解的自动代理
<aop:aspectj-autoproxy/>
6)AspectJ的AOP的注解
@Aspect:定义切面类的注解
通知类型:
- @Before :前置通知
- @AfterReturing :后置通知
- @Around :环绕通知
- @After :最终通知
- @AfterThrowing :异常抛出通知.
- @Pointcut:定义切入点的注解
7)编写切面类
@Aspect
public class MyAspectAnno {
@Before("MyAspectAnno.pointcut1()")
public void before() {
System.out.println("前置通知===========");
}
@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.save(..))")
private void pointcut1() {
}
}
8)配置切面
<!-- 配置切面类 -->
<bean id="myAspectAnno" class="cn.itcast.spring.demo4.MyAspectAnno"></bean>
9)其它通知的注解
@Aspect
public class MyAspectAnno {
@Before("MyAspectAnno.pointcut1()")
public void before() {
System.out.println("前置通知===========");
}
@AfterReturning("MyAspectAnno.pointcut2()")
public void afterReturning() {
System.out.println("后置通知===========");
}
@Around("MyAspectAnno.pointcut3()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前通知==========");
Object obj = joinPoint.proceed();
System.out.println("环绕后通知==========");
return obj;
}
@AfterThrowing("MyAspectAnno.pointcut4()")
public void afterThrowing() {
System.out.println("异常抛出通知========");
}
@After("MyAspectAnno.pointcut4()")
public void after() {
System.out.println("最终通知==========");
}
@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.save(..))")
private void pointcut1() {
}
@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.update(..))")
private void pointcut2() {
}
@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.delete(..))")
private void pointcut3() {
}
@Pointcut("execution(* cn.itcast.spring.demo4.ProductDao.find(..))")
private void pointcut4() {
}
}