1. 程式人生 > >Spring原始碼:Advice介面

Spring原始碼:Advice介面

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;
}