XML里的id=””记得全小写

经过AOP的配置后,可以切入日志功能、访问切入、事务管理、性能监测等功能。

首先实现这个织入增强需要的jar包,除了常用的

com.springsource.org.apache.commons.logging-1.1.1.jar,

com.springsource.org.apache.log4j-1.2.15.jar,

spring-beans-3.2.0.RELEASE.jar,

spring-context-3.2.0.RELEASE.jar,

spring-core-3.2.0.RELEASE.jar,

spring-expression-3.2.0.RELEASE.jar之外还需要

spring-aop-3.2.0.RELEASE.jar,

com.springsource.org.aopalliance-1.0.0.jar,(aop联合jar)

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar(织入方向jar)三个包。

然后我有一个接口

public interface Hello {

public void say();

}

和一个实现类

public class HelloImpl implements Hello{

public void say(){

System.out.println("执行say方法");

}

}

和两个增强类

前置增强:

public class LogBefor implements MethodBeforeAdvice{

@Override

public void before(Method method, Object[] args, Object target)

throws Throwable {

System.out.println(method);

System.out.println(args);

System.out.println(target);

}

}

后置增强:

public class LogAfter implements AfterReturningAdvice{

@Override

public void afterReturning(Object returnValue, Method method,

Object[] args, Object target) throws Throwable {

System.out.println("返回值"+returnValue);

System.out.println("方法:"+method);

System.out.println("参数:"+args);

System.out.println("被代理对象:"+target);

}

}

接下来还需要在Spring配置文件中beans元素中需要添加aop的名称空间,以导入与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">

这里比之前的多了:xmlns:aop="http://www.springframework.org/schema/aop"

在xsi:schemaLocation里多了两个

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd;

接下来在Spring配置文件中实现AOP配置,如我的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">

<bean id="hello" class="cn.cnti.aop.HelloImpl"></bean>

<!-- 增强类 -->

<bean id="before" class="cn.cnti.aop.LogBefor">

</bean>

<bean id="after" class="cn.cnti.aop.LogAfter">

</bean>

<aop:config>

<!-- 定义切入点 -->

<aop:pointcut id="pointcut"

expression="execution(public void say())"/>

<aop:advisor advice-ref="before" pointcut-ref="pointcut"/>

<aop:advisor advice-ref="after" pointcut-ref="pointcut"/>

</aop:config>

</beans>

如果记不清楚的话,spring-framework-3.2.0.RELEASE-dist→spring-framework-3.2.0.RELEASE→docs→spring-framework-reference→html→aop.html打开后搜索aop会有模板。

其中execution是切入点指示符,它的括号中是一个切入点表达式,可以配置要切入的方法,切入点表达式支持模糊匹配:

Public * say(entity.User):”*”表示匹配所有类型的返回值

Public void *(entity.User):”*”表示匹配所有方法名。

Public void say(..):”..”表示匹配所有参数个数和类型。

* cn.jnti.service.*.*(..):这个表达式匹配cn.jnti.service包下所有类的所有方法。

* cn.jnti.service..*.*(..):这个表达式匹配cn.jnti.service包及其子包下所有类的所有方法。

等等,还有许多。

最后我们测试一下:

@Test

public void mtest(){

BeanFactory bf=new  ClassPathXmlApplicationContext("appContext.xml");

Hello h = (Hello) bf.getBean("hello");

h.say();

}

***********************************************************************************************************

如果想实现日志输出的话,在这个原有jar包的基础上需要

cglib-nodep-2.2.3.jar和org.springframework.asm-3.1.1.RELEASE.jar包

然后再前置增强和后置增强里各加一个静态常量:

Private static final Logger log=Logger.getLogger(LogBefor.class);和

Private static final Logger log=Logger.getLogger(LogAfter.class);

然后在方法里直接用lo.info(“调用”+target6”的”+method.getName()+”方法”+”参数是:”+Arrays.toString(args));就行了。

*****************************************************************************************************************************************

环绕增强:

首先有一个一个User类里面有name,和price属性。

有一个接口:

public interface UserService {

Object save(User user);

}

有一个实现类:

public class UserServiceImpl implements UserService {

@Override

public Object save(User user) {

System.out.println(user.getName()+"存了"+user.getPrice()+"$");

return true;

}

}

我的循环增强类实现MethodInterceptor(是在importorg.aopalliance.intercept.MethodInterceptor包下):

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

public class Surround implements MethodInterceptor{

@Override

public Object invoke(MethodInvocation arg0) throws Throwable {

System.out.println("我进循环增强了!");

Object[] objects = arg0.getArguments();

for (Object obj : objects) {

System.out.println(obj);

}

User user=(User) objects[0];

if(user.getPrice()<0){

System.out.println("存款不能为负数!");

return false;

}else{

//放行

return arg0.proceed();

}

}

}

我的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">

<bean id="usersericeimpl" class="cn.cnti.aop.UserServiceImpl">

</bean>

<bean id="surround" class="cn.cnti.aop.Surround"></bean>

<!-- 增强类 -->

<aop:config>

<!-- 定义切入点 -->

<aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

<aop:advisor advice-ref="surround" pointcut-ref="pointcut" />

</aop:config>

我的测试类:

@Test

public void testAround(){

BeanFactory bf=new ClassPathXmlApplicationContext("appContext.xml");

UserService us= (UserService) bf.getBean("usersericeimpl");

Object object = us.save(new User("sp",101));

System.out.println(object);

}

***********************************************************************************************************

异常抛出增强:

只需要有一个类实现ThrowsAdvice接口:

import java.lang.reflect.Method;

import org.springframework.aop.ThrowsAdvice;

public class ErrorLogger implements ThrowsAdvice{

public void afterThrowing(Method method,Object[] args,Object target,Exception e){

System.out.println("调用"+target+"的"+method.getName()+"方法时,发生异常"+e);

}

}

,但是

通过ThrowsAdvice接口实现异常抛出增强。ThrowsAdvice接口中并没有定义任何方法。

但是我们在定义异常抛出的增强方法时必须遵守以下方法签名。

afterThrowing(Method method,Object[] args,Object target,Exception e)

这里规定了方法名必须是afterThrowing。方法的入参只有最后一个是必须的,前三个入参是可选的,

但是前3个参数要么都提供,要么一个也不提供。

然后在xml配置里再加上:

<!-- 异常抛出增强 -->

<bean id="errorlogger" class="cn.cnti.aop.ErrorLogger"></bean>

<aop:config>

<!-- 定义切入点 -->

<aop:pointcut id="pointcut" expression="execution(* cn.cnti.aop..*.*(..))" />

<aop:advisor advice-ref="errorlogger" pointcut-ref="pointcut" />

</aop:config>

因为没有异常的话是不会看到效果的,所以要手动制造一个异常:

public Object save(User user) {

System.out.println(user.getName()+"存了"+user.getPrice()+"$");

int a=1/0;

return true;

}

******************************************************************************************************

使用注解标注增强:

我的注解增强类:

package cn.cnti.annotation;

import org.aspectj.lang.annotation.AfterReturning;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

//@Aspect注解将UserBizAdvice定义为切面

@Aspect

public class UserBizAdvice{

//前置增强

@Before("execution(* cn.cnti.annotation..*.*(..))")

public void before(){

System.out.println("即将调用业务方法!");

}

//后置增强

@AfterReturning("execution(* cn.cnti.annotation..*.*(..))")

public void afterReturning(){

System.out.println("后置增强");

}

}

配置文件除了要导入aop命名空间外,只需要在配置文件中添加

<aop:aspectj-autoproxy />元素,即可启用对于@AspectJ注解的支持,Spring将自动为匹配的Bean创建代理,为了注册定义好的切面,还要在Spring配置文件中声明UserBizAdvice的一个实例(不需要被其他Bean引用,可以不指定Id属性);

我的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"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

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.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

">

<bean id="userserviceimpl" class="cn.cnti.annotation.UserServiceImpl"></bean>

<aop:aspectj-autoproxy />

<bean class="cn.cnti.annotation.UserBizAdvice"></bean>

****************************************************************************************************************

</beans>

上一个注解标注增强还可以这么用:

@Aspect//@Aspect注解将UserBizAdvice定义为切面

public class UserBizAdvice2{

@Pointcut("execution(public void save(..))")

public void cut(){

}

//前置增强

@Before("cut()")

public void before(){

System.out.println("wo shi UserBizAdvice2");

System.out.println("即将调用业务方法!");

}

//后置增强

@AfterReturning("cut()")

public void afterReturning(){

System.out.println("wo shi UserBizAdvice2");

System.out.println("后置增强");

}

}

其他不变!

***************************************************************************************************************

使用注解定义其他类型的增强:

我的注解增强类:

@Aspect//@Aspect注解将UserBizAdvice定义为切面

public class UserBizAdvice2{

@Pointcut("execution(public void save(..))")

public void cut(){

}

//前置增强

@Before("cut()")

public void before(JoinPoint jp){

System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入参:"+Arrays.toString(jp.getArgs()));

System.out.println("前置增强");

}

//后置增强

@AfterReturning(pointcut="cut()",returning="returnValue")

public void afterReturning(JoinPoint jp,Object returnValue){

System.out.println("返回值是:"+returnValue);

System.out.println("后置增强");

}

@AfterThrowing(pointcut="cut()",throwing="ex")

public void afterThrowing(JoinPoint jp,Exception ex){

System.out.println("异常了:"+ex);

}

//ProceedingJoinPoint是JoinPoint的子接口,它的proceed()方法可以调用真正的目标方法,从而达到对连接点的完全控制

@Around("cut()")

public Object around(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("环绕前");

Object obj = pjp.proceed();

System.out.println("环绕后");

return obj;

}

//@AspectJ还提供了一种最终增强类型,其特点是无论方法抛出异常还是正常退出,该增强都会得到执行,类似于异常处理机制中finally块的作用,一般用于释放资源。

@After("cut()")

public void after(){

System.out.println("最终增强!");

}

}

XML同上一个XML没有变化,唯一注意的一点是:<aop:aspectj-autoproxy />

自动代理默认是对接口的代理,我们测试的时候:

BeanFactory bf=new ClassPathXmlApplicationContext("annotationContext.xml");

UserService  service = (UserService) bf.getBean("userserviceimpl");

service.save(new User("admin","pwd"));

都是强转成接口,然后用接口接受,

如果想对类进行代理,可以这么设置:

<aop:aspectj-autoproxy proxy-target-class="true"/>

*****************************************************************************************************************

使用Schema配置其他增强类型:

我的增强类:

public class UserBizAdvice {

public void before(JoinPoint jp){

System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法.方法入参:"+Arrays.toString(jp.getArgs()));

System.out.println("前置增强");

}

public void afterReturning(JoinPoint jp,Object returnValue){

System.out.println("返回值是:"+returnValue);

System.out.println("后置增强");

}

public void afterThrowing(JoinPoint jp,Exception ex){

System.out.println("异常了:"+ex);

}

public Object around(ProceedingJoinPoint pjp) throws Throwable{

System.out.println("环绕前");

Object obj = pjp.proceed();

System.out.println("环绕后");

return obj;

}

public void after(){

System.out.println("最终增强!");

}

}

然后我的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"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

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.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd

">

<bean id="userserviceimpl" class="cn.cnti.schema.UserServiceImpl"></bean>

<bean id="advice" class="cn.cnti.schema.UserBizAdvice"></bean>

<aop:config>

<aop:pointcut expression="execution(* cn.cnti.schema..*.*(..))" id="pointcut"/>

<aop:aspect ref="advice">

<aop:before method="before" pointcut-ref="pointcut"/>

<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="returnValue"/>//和类里的Object returnValue对应

<aop:after method="after" pointcut-ref="pointcut"/>

<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>

<aop:around method="around" pointcut-ref="pointcut"/>

</aop:aspect>

</aop:config>

</beans>

Spring配置AOP实现定义切入点和织入增强的更多相关文章

  1. Spring AOP 之编译期织入、装载期织入、运行时织入(转)

    https://blog.csdn.net/wenbingoon/article/details/22888619 一   前言 AOP 实现的关键就在于 AOP 框架自动创建的 AOP 代理,AOP ...

  2. Spring配置--Aop配置详情

    首先我们来看一下官方文档所给我们的关于AOP的一些概念性词语的解释: 切面(Aspect):一个关注点的模块化,这个关注点可能会横切多个对象.事务管理是J2EE应用中一个关于横切关注点的很好的例子.在 ...

  3. Spring的AOP AspectJ切入点语法详解(转)

    一.Spring AOP支持的AspectJ切入点指示符 切入点指示符用来指示切入点表达式目的,在Spring AOP中目前只有执行方法这一个连接点,Spring AOP支持的AspectJ切入点指示 ...

  4. Spring 梳理 - AOP那些学术概念—通知、增强处理连接点(JoinPoint)切面(Aspect)

    Spring  AOP那些学术概念—通知.增强处理连接点(JoinPoint)切面(Aspect)   1.我所知道的AOP 初看起来,上来就是一大堆的术语,而且还有个拉风的名字,面向切面编程,都说是 ...

  5. spring相关—AOP编程—切入点、连接点

    1 切入点表达式 1.1 作用 通过表达式的方式定位一个或多个具体的连接点. 1.2 语法细节 ①切入点表达式的语法格式 execution([权限修饰符] [返回值类型] [简单类名/全类名] [方 ...

  6. Spring的AOP机制---- 切入点表达式---- 切入点表达式

    3333钱钱钱钱钱钱钱钱钱钱钱钱钱钱钱

  7. Spring 之AOP AspectJ切入点语法详解

    记录一下,以后学习 https://blog.csdn.net/zhengchao1991/article/details/53391244

  8. Spring:AOP面向切面编程

    AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果. AOP是软件开发思想阶段性的产物,我们比较熟悉面向过程O ...

  9. 【spring源码学习】spring的AOP面向切面编程的实现解析

    一:Advice(通知)(1)定义在连接点做什么,为切面增强提供织入接口.在spring aop中主要描述围绕方法调用而注入的切面行为.(2)spring定义了几个时刻织入增强行为的接口  => ...

随机推荐

  1. 巴特沃斯(Butterworth)滤波器 (1)

    下面深入浅出讲一下Butterworth原理及其代码编写. 1. 首先考虑一个归一化的低通滤波器(截止频率是1),其幅度公式如下: 当n->∞时,得到一个理想的低通滤波反馈: ω<1时,增 ...

  2. 2016 Multi-University Training Contest 1 C.Game

    Game Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submis ...

  3. 点 击 直 接加我QQ的功能

    <a target="_blank" href="tencent://message/?uin=2814920598&Site=&Menu=yes& ...

  4. js面向对象总结(一)

    在 js 中,对象由特性(attribute)构成,特性可以是原始值,也可以是引用值.如果特性存放的是函数,它将被看作对象的方法(method),否则该特性被看作对象的属性(property).在js ...

  5. tornado 学习笔记8 模板以及UI

          Tornado 包含一个简单.快速而且灵活的模板语言.       Tornado同样可以使用任何其他的python模板语言,虽然没有集成这些模板语言进RequestHandler.ren ...

  6. java文件下载,上传,解压方法

    1.文件下载(亲测可用) private static final int BUFFER = 2 * 1024;// 缓冲区大小(2k)private boolean isSuccess = true ...

  7. ZK 页面间参数传递

    1.execution.sendRedirect(url) 当使用方法execution.sendRedirect(url)进行页面跳转时,在url中添加参数:url?test=5: 跳转页面获取参数 ...

  8. #20145205 《Java程序设计》第4周学习总结

    教材学习内容总结 1.面对对象中,因为我们需要设计多个模块,但是有不能像C语言中那样进行分块设计,所以我们用父类和子类进行模块的设计,我们在设计一个较大的程序时,在一个项目中建立不同的文件,用关键字e ...

  9. SSH配置中出现问题

    问题1:org.springframework.beans.factory.NoSuchBeanDefinitionException: org.springframework.beans.facto ...

  10. android ANR产生原因和解决办法【转】

    ANR (Application Not Responding) ANR定义:在Android上,如果你的应用程序有一段时间响应不够灵敏,系统会向用户显示一个对话框,这个对话框称作应用程序无响应(AN ...