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. What is a Database Trigger?

    Link: http://www.essentialsql.com/what-is-a-database-trigger/ Copy... What is a Database Trigger? A ...

  2. PHP文件上传

    前台页代码: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> </h ...

  3. Unity3D连接sqlite数据库操作C#版

    unity3d有自己对应的sqlite.dll分别需要三个文件 1.Mono.Data.Sqlite.dll 在unity安装文件“Unity\Editor\Data\MonoBleedingEdge ...

  4. android中的回调简单认识

    首先说一下最抽象的形式--2个类,A类和B类.A类含有1个接口.1个接口变量.(可能含有)1个为接口变量赋值的方法以及1个会使用接口变量的"地方";B类实现A中的接口,(可能)含有 ...

  5. 7.echo(),print(),print_r()的区别

    echo是PHP语句, print和print_r是函数,语句没有返回值,函数可以有返回值(即便没有用) print()    只能打印出简单类型变量的值(如int,string) print_r() ...

  6. final阶段成员贡献分

    项目名:连连看 组名:天天向上 组长:王森 组员:张政.张金生.林莉.胡丽娜 final阶段各组员的贡献分分配如下: 姓名 个人工作量 组长评价 个人评价 团队贡献总分 张政 11 7 6 6.00 ...

  7. 分享一个前辈的NPOIhelper

    即拿即用: 首先要下载npoi的dll,此不赘述,接着添加引用: using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel ...

  8. hibernate学习(9)——日志,一对一,二级缓存

    1.Hibernate中的日志 1  slf4j 核心jar  : slf4j-api-1.6.1.jar .slf4j是日志框架,将其他优秀的日志第三方进行整合. 整合导入jar包 log4j 核心 ...

  9. c语言编程

    1.常量和变量:变量是一块内存空间,该内存空间有类型约束,该内存中存放的数据可变. 变量三要素:类型,名称,值.常量:常量的数据永远不变,a:自变量,b:符合常量,c:预定义常量. 2.运算符和返回类 ...

  10. 1.Maven的安装以及本地仓库的配置

    安装: maven下载地址:http://maven.apache.org/release-notes-all.html 然后解压,配置环境变量   MAVEN_HOME,并添加到path中.验证是否 ...