Spring AOP Advice接口-MethodBeforeAdvice+AfterReturningAdvice

来源:互联网 发布:js console.log 编辑:程序博客网 时间:2024/06/05 02:39
接口说明:
MethodBeforeAdvice
AfterReturningAdvice
目标方法执行前被调用,通过MethodBeforeAdvice接口实现。
MethodBeforeAdvice接口定义了before(Method method,Object[]args,Object target),这个是具体被调用的方法。
目标方法执行后被调用,通过 AfterReturningAdvice 接口实现。
MethodBeforeAdvice接口定义了afterReturning(Object arg0, Method arg1, Object[] arg2,Object arg3),这个是具体被调用的方法。

使用示例:

1.创建Java工程
创建一个Java工程,配置Spring框架,检查是否引入Spring AOP包,没有则引入Spring AOP相应的包
引入方式

2.创建接口和实现类
//创建一个接口,这个接口用来定义哪些方法要拦截package com.entity;public interface IHello {public void sayHello(String name);}

//创建一个实现类,实现IHello接口,这个类的sayHello方法就是具体被调用的方法,也就是拦截目标package com.entity;public class Hello implements IHello { public void sayHello(String name) { System.out.println("你好"+name); }}

//创建一个拦截的实现类,实现MethodBeforeAdvice接口,重写before()方法,这个是具体被调用来做执行前操作的类package com.entity;import java.lang.reflect.Method;import org.springframework.aop.MethodBeforeAdvice;public class SayBeforeAdvice implements MethodBeforeAdvice { public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("在方法执行前做的事情!"); }}

//创建一个拦截的实现类,实现AfterReturningAdvice接口,重写 afterReturning ()方法,这个是具体被调用来做执行后操作的类package com.entity;import java.lang.reflect.Method;import org.springframework.aop.AfterReturningAdvice;public class sayAfterAdvice implements AfterReturningAdvice { public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("执行后做的事情!"); }}

//创建测试类,在main方法里获得接口的代理实例,调用其sayHello()方法public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); IHello iHello=(IHello) context.getBean("helloProxy"); iHello.sayHello("Baby"); }


3.配置applicationContext.xml文件

<!-- 设置AOP Advices --><!--配置类--><bean id="hello" class="com.entity.Hello"></bean><bean id="sba" class="com.entity.SayBeforeAdvice"></bean><bean id="saa" class="com.entity.sayAfterAdvice"></bean><!--配置代理类--><bean id="helloProxy" class="org.springframework.aop.framework.ProxyFactoryBean"><!--如果没有找到ProxyFactoryBean类,则参考步骤1,引入Spring AOP相应的包--> <!-- 指定代理接口,value值要绝对路径 --> <property name="proxyInterfaces"> <value>com.entity.IHello</value> </property> <!-- 指定目标,这里用的是id名--> <property name="target"> <ref bean="hello"/> </property> <!-- 拦截实现类,可以多个 --> <property name="interceptorNames"> <list> <value>sba</value> </list> </property></bean>


4.运行效果



 
0 0
原创粉丝点击