1.Advice接口使用
Advice是对附加方法(被代理的方法前后需要执行的)的描述。
在Spring AOP中支持4中类型的通知:
1:before advice 在方法执行前执行。
2:after returning advice 在方法执行后返回一个结果后执行。
3:after throwing advice 在方法执行过程中抛出异常的时候执行。
4:Around advice 在方法执行前后和抛出异常时执行,相当于综合了以上三种通知
student类
public class Student {
private String name;
private Integer age;
public Student() {
}
//getter and setter......
public void print() {
System.out.println(this.name + "---" + this.age);
}
}
通知
public class SpringBeforeAdviceMethod implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("SpringBeforeAdviceMethod before......");
}
}
public class SpringAfterAdviceMethod implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("SpringAfterAdviceMethod after ......");
}
}
配置xml文件
<context:component-scan base-package="com.spring.aop"/>
<bean id="springBeforeAdviceMethod" class="com.spring.aop.advice.SpringBeforeAdviceMethod"/>
<bean id="springAfterAdviceMethod" class="com.spring.aop.advice.SpringAfterAdviceMethod"/>
<bean id="student" class="com.spring.aop.advice.Student">
<property name="name" value="zhuqiuhui"/>
<property name="age" value="19"/>
</bean>
<!--定义代理类-->
<bean id="studentProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="student"/>
<property name="interceptorNames">
<list>
<value>springBeforeAdviceMethod</value>
<value>springAfterAdviceMethod</value>
</list>
</property>
</bean>
main方法
public class AopMain {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) applicationContext.getBean("studentProxy");
student.print();
}
}
2.Advice接口源码分析
package org.aopalliance.aop;
public interface Advice {
}
##2.1 MethodBeforeAdvice接口
public interface BeforeAdvice extends Advice {
}
public interface MethodBeforeAdvice extends BeforeAdvice {
void before(Method method, Object[] args, Object target) throws Throwable;
}
2.2 AfterReturningAdvice接口
public interface AfterAdvice extends Advice {
}
public interface AfterReturningAdvice extends AfterAdvice {
void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable;
}
2.3 ThrowsAdvice接口
public interface ThrowsAdvice extends AfterAdvice {
}
2.4 MethodInterceptor接口
public interface Interceptor extends Advice {
}
public interface MethodInterceptor extends Interceptor {
//invoke方法内部会调用代理的那个方法
Object invoke(MethodInvocation invocation) throws Throwable;
}