ITeye博客

spring aop

hance1000000 · 2009-08-21 16:02 · spring · Markdown

方法1: 用到aspectjrt.jar

在spring的配置文件中使用标签aop:config

// 在目标对象前后 需要 要执行的方法 好像在aop术语叫advice

//目标对象,在默认情况下必须实现接口,采用jdk动态代理实现,如果没有实现接口必须引入CGLIB库,则使用cglib代理

aop:config <aop:aspect id="security" ref="securityHandler">

//aop术语叫切面,包括切点和advice(包括什么时候执行)

首先我解释一下execution(* com.evan.crm.service..(..))中几个通配符的含义:

第一个 * —— 通配 任意返回值类型 第二个 * —— 通配 包com.evan.crm.service下的任意class 第三个 * —— 通配 包com.evan.crm.service下的任意class的任意方法 第四个 .. —— 通配 方法可以有0个或多个参数

<aop:pointcut id="allAddMethod" expression="execution(* com.bjsxt.spring.UserManagerImpl.add*(..))"/>

//对哪些类进行代理 <aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>

//定义了类中的checkSecurity方法 在usermanagerimpl中 所有以add开头的方法前执行 <aop:before method="dobefore" pointcut-ref="allAddMethod"/>

//同上 </aop:aspect> </aop:config>

这样在通过BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

factory.getBean("userManager")得到类 调用其方法的时候 会先执行advice即checkSecurity方法

方法2

自己定义类,实现接口。

(这2个比较常用,其他的暂时不列)

org.springframework.aop.AfterReturningAdvice 相当于after

要实现afterReturning方法。

org.springframework.aop.MethodBeforeAdvice 相当于before
要实现before 方法。

public class AfterProxy implements AfterReturningAdvice {

public void afterReturning(Object arg0, Method arg1, Object arg2, Object arg3) throws Throwable { System.out.println("after"); System.out.println("要调用方法的名称:" + arg1.getName()); System.out.println("要调用方法的参数:" + arg2.toString()); System.out.println("目标对象:" + arg3); System.out.println("返回值:" + arg0);

}

}

public class BeforeProxy implements MethodBeforeAdvice {

public void before(Method arg0, Object arg1, Object arg2) throws Throwable { System.out.println("before___"); System.out.println("要调用方法的名称:" + arg0.getName()); System.out.println("要调用方法的参数:" + arg1.toString()); System.out.println("目标对象" + arg2); }

}

接下来在spring配置文件中配置:

所要代理的类

id名字必须是before 不能变。下同理

com.pojo.Dog 目标接口 //前面定义的代理的类 拦截器名字 即 调用什么方法。 这里是调用的before

                                                         即在调用mydog的方法是 先执行before对应的bean里的方法

com.pojo.Dog after

ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); Dog dog = (Dog) context.getBean("beforeProxy");

这样在调用dog的方法的时候 就会先执行beforeProxy里的方法 然后在执行dog的方法.

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/pjw0221/archive/2009/07/17/4358364.aspx

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。