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. Session和Cache的区别

    以前实现数据的缓存有很多种方法,有客户端的Cookie,有服务器端的Session和Application.其中Cookie是保存在客户端的一组数据,主要用来保存用户名等个人信息.Session则保存 ...

  2. 惠普披甲过VR寒冬,花费巨资开发VR游戏

         2016被称为VR元年,各大公司都在积极推动该领域的研究,其中HTC.0culus.索尼的成绩是最高的,不仅推出了自家研发的头显,而且销量还很可观.惠普在VR领域自然也有所投入,但是并没有比 ...

  3. Android入门(四):链接接口组件和程序代码

    编写好layout中的接口组件之后,下一步就是编写控制接口组件的程序代码.上一章,我们使用了三种接口组件,在使用者输入性别和年龄之后点击“健康建议按钮”,程序会读取用户所填入的性别和年龄,然后显示判断 ...

  4. css选择器总结

    (一)选择器优先级: 不同级别 1. 在属性后面使用 !important 会覆盖页面内任何位置定义的元素样式. 2.作为style属性写在元素内的样式 3.id选择器 4.类选择器 5.标签选择器 ...

  5. DataTable 的使用

    DataTable CFHMXdt = new DataTable(); CFHMXdt.Columns.Add("group", typeof(System.String));  ...

  6. Spark 架构

    本文转之Pivotal的一个工程师的博客.觉得极好.   作者本人经常在StackOverflow上回答一个关系Spark架构的问题,发现整个互联网都没有一篇文章能对Spark总体架构进行很好的描述, ...

  7. js获取浏览器前缀

    <script> var div = null; var _prefix = (function (temp) { var prefix = ["webkit", &q ...

  8. IBatis添加信息返当前添加对象ID

      在Ibatis中,insert()的返回值为一个Object的主键,其实这个Object的主键是这样的来的:如果在bean的xml文件中设置了插入的keyProperty,则insert()方法返 ...

  9. js事件机制——事件冒泡和捕获

    概念:当给子元素和父元素定义了相同的事件,比如都定义了onclick事件,点击子元素时,父元素的onclick事件也会被触发.js里称这种事件连续发生的机制为事件冒泡或者事件捕获. IE浏览器:事件从 ...

  10. 泛型:HashMap的用法--输入字母输出数目

    public static void main(String[] args) { Map <String ,Integer> m =new HashMap<String , Inte ...