spring AOP (使用AspectJ的注解方式 的aop实现) (6)
前面的动态代理中,可以有前置通知,后置通知,返回通知,异常通知
在spring2.0以后,可以使用基于 AspectJ 注解或基于 XML 配置的 AOP
- AspectJ:Java 社区里最完整最流行的 AOP 框架.
一、在 Spring 中启用 AspectJ 注解支持
- 1要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库: aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar
maven 引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
<scope>runtime</scope>
</dependency>
- 2将 aop Schema 添加到 根元素中.
- 3要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素
<!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 4当 Spring IOC 容器侦测到 Bean 配置文件中的 aop:aspectj-autoproxy 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.
二、AspectJ 支持 5 种类型的通知注解:
- @Before: 前置通知, 在方法执行之前执行
- @After: 后置通知, 在方法执行之后执行
- @AfterRunning: 返回通知, 在方法返回结果之后执行
- @AfterThrowing: 异常通知, 在方法抛出异常之后
- @Around: 环绕通知, 围绕着方法执行
2.1、使用之前的 计算器接口和实现类 ArithmeticCalculator.java , ArithmeticCalculatorImpl.java
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{}
2.2、在xml中增加扫描注解和aspectj的支持
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.hp.spring.aop.annotation"></context:component-scan>
<!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
2.3、编写切面类,定义各种通知
@Aspect //注解定义切面
@Component
public class LoggingAspect {
//前置通知
@Before("execution(public int com.hp.spring.aop.annatation.ArithmeticCalculator.*(int, int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object [] args = joinPoint.getArgs();
System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
}
//前置通知
@After("execution(* com.hp.spring.aop.annatation.*.*(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends");
}
}
由于@before 和@after的表达式都一样,所以spring支持对表达式进行抽取成一个方法,抽取后的代码如下:
package com.hp.spring.aop.annotation;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 可以使用 @Order 注解指定切面的优先级, 值越小优先级越高
*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码.
* 使用 @Pointcut 来声明切入点表达式.
* 后面的其他通知直接使用方法名来引用当前的切入点表达式.
*/
@Pointcut("execution(public int com.hp.spring.aop.annotation.ArithmeticCalculator.*(..))")
public void declareJointPointExpression(){}
/**
* 在 com.hp.spring.aop.annotation.ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
*/
@Before("declareJointPointExpression()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object [] args = joinPoint.getArgs();
System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
}
/**
* 在方法执行之后执行的代码. 无论该方法是否出现异常
*/
@After("declareJointPointExpression()")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends");
}
/**
* 在方法法正常结束受执行的代码
* 返回通知是可以访问到方法的返回值的!
*/
@AfterReturning(value="declareJointPointExpression()",
returning="result")
public void afterReturning(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends with " + result);
}
/**
* 在目标方法出现异常时会执行的代码.
* 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
*/
@AfterThrowing(value="declareJointPointExpression()",
throwing="e")
public void afterThrowing(JoinPoint joinPoint, Exception e){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " occurs excetion:" + e);
}
/**
* 环绕通知需要携带 ProceedingJoinPoint 类型的参数.
* 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
* 且环绕通知必须有返回值, 返回值即为目标方法的返回值
*/
/*
@Around("execution(public int com.hp.spring.aop.annotation.ArithmeticCalculator.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjd){
Object result = null;
String methodName = pjd.getSignature().getName();
try {
//前置通知
System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
//执行目标方法
result = pjd.proceed();
//返回通知
System.out.println("The method " + methodName + " ends with " + result);
} catch (Throwable e) {
//异常通知
System.out.println("The method " + methodName + " occurs exception:" + e);
throw new RuntimeException(e);
}
//后置通知
System.out.println("The method " + methodName + " ends");
return result;
}
*/
}
- 切面二
package com.hp.spring.aop.annotation;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Aspect
@Component
public class VlidationAspect {
@Before("com.hp.spring.aop.annotation.LoggingAspect.declareJointPointExpression()")
public void validateArgs(JoinPoint joinPoint){
System.out.println("-->validate:" + Arrays.asList(joinPoint.getArgs()));
}
}
- 测试类
package com.hp.spring.aop.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aspectj.xml");
ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
System.out.println(arithmeticCalculator.getClass().getName());
int result = arithmeticCalculator.add(1, 2);
System.out.println("result:" + result);
result = arithmeticCalculator.div(1000, 10);
System.out.println("result:" + result);
}
}
打印出:
com.sun.proxy.$Proxy12
-->validate:[1, 2]
The method add begins with [1, 2]
The method add ends
The method add ends with 3
result:3
-->validate:[1000, 10]
The method div begins with [1000, 10]
The method div ends
The method div ends with 100
result:100
打印的日志中,可以看出,跟动态代理一样,可以定义各类通知。
整个系列项目代码: http://git.oschina.net/nmc5/spring
spring AOP (使用AspectJ的注解方式 的aop实现) (6)的更多相关文章
- 基于AspectJ的注解方式进行AOP开发
-------------------siwuxie095 基于 AspectJ 的注解方式进行 AOP 开发 ...
- AOP——基于AspectJ的注解来实现AOP操作
1.使用注解方式实现AOP操作 第一步:创建对象 <!-- 创建对象 --> <bean id="book" class="com.bjxb.aop.B ...
- Spring的AOP基于AspectJ的注解方式开发2
参考自黑马培训机构 上一篇博客提到了在配置文件中开启aop的注解开发,以及简单使用了@Before,@Aspect 这是为了告诉spring为前置通知和切面类 接下来介绍aop的注解的通知类型,和切入 ...
- Spring的AOP基于AspectJ的注解方式开发1
参考自黑马培训机构 创建项目,引入jar包 编写目标类,切面类并完成配置 package spring.day2_aop2; /* * 编写目标类 */ public class OrderDao { ...
- Spring的AOP基于AspectJ的注解方式开发3
上上偏博客介绍了@Aspect,@Before 上篇博客介绍了spring的AOP开发的注解通知类型:@Before,@AfterThrowing,@After,@AfterReturning,@Ar ...
- spring框架之AspectJ的XML方式完成AOP的开发
1. 步骤一:创建JavaWEB项目,引入具体的开发的jar包 * 先引入Spring框架开发的基本开发包 * 再引入Spring框架的AOP的开发包 * spring的传统AOP的开发的包 * sp ...
- spring AOP (使用AspectJ的xml方式 的aop实现) (7)
目录 一.定义计算器接口跟实现类 二.定义两个切面,日志切面和验证切面 三.在xml中配置切面 四.测试类 一.定义计算器接口跟实现类 public interface ArithmeticCalcu ...
- spring学习(六)注解方式实现AOP
一.导包(导入maven的依赖) <?xml version="1.0" encoding="UTF-8"?> <project xmlns= ...
- (转)Spring使用AspectJ进行AOP的开发:注解方式
http://blog.csdn.net/yerenyuan_pku/article/details/69790950 Spring使用AspectJ进行AOP的开发:注解方式 之前我已讲过Sprin ...
随机推荐
- SCP-bzoj-1057
项目编号:bzoj-1057 项目等级:Safe 项目描述: 戳这里 特殊收容措施: 首先枚举最左上角的点(记为(1,1))是黑点还是白点,这样就可以把与(1,1)不在同一对角线系的格点颜色翻转(形式 ...
- Python基础教程(011)--程序开发中的错误及原因
前言 排查代码开发中的错误 内容 1,编写的程序不能正常执行,或者执行的结果不是我们期望的 2,俗称bug,是程序开发常见的,初学常见的原因有 手误 对已经学习的知识点理解不足 对语音还有需要学习和提 ...
- mysql添加索引和sql分析
mysql索引操作 查看索引 show indexes from students; #students为表名 mysql添加索引命令 创建索引 .PRIMARY KEY(主键索引) mysql> ...
- 探索Redis设计与实现12:浅析Redis主从复制
本文转自互联网 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial ...
- 大数据学习笔记之Hadoop(一):Hadoop入门
文章目录 大数据概论 一.大数据概念 二.大数据的特点 三.大数据能干啥? 四.大数据发展前景 五.企业数据部的业务流程分析 六.企业数据部的一般组织结构 Hadoop(入门) 一 从Hadoop框架 ...
- C++构造函数异常(一)
C++ 构造函数的异常是一个比较难缠的问题,很多时候,我们可能不去考虑这些问题,如果被问到,有人可能会说使用RAII管理资源. 但你真的考虑过如果构造函数失败了,到底会发生什么吗,前面构造成功的成员. ...
- web跨域
之前对于跨域相关的知识一致都很零碎,正好现在的代码中用到了跨域相关的,现在来对这些知识做一个汇总整理,方便自己查看,说不定也可能对你有所帮助. 本篇主要内容如下: 浏览器同源策略 http 请求跨域 ...
- filter 在CSS用的效果
滤镜说明: Alpha:设置透明层次 blur:创建高速度移动效果,即模糊效果 Chroma:制作专用颜色透明 DropShadow:创建对象的固定影子 FlipH:创建水平镜像图片 FlipV:创建 ...
- libvirt虚拟机管理常用指令
创建虚拟机 virt-install virt-install --connect qemu:///system -n $NAME -r $MEM -f $DISK -s $DISK_SIZE --v ...
- php &引用符的注意情况