Spring的Aspect的簡單學習

package aspectj;
public interface MyInterface {
    void objectMethod(String in);
}

package aspectj;
public class MyClass implements MyInterface {
    @Override
    public void objectMethod(String in) {
        System.out.println(in);
        throw new RuntimeException();
    }
}

package aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class MyAdvice {
    @Around(value = "execution(public * *(..))")
    public Object myAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        try{
            System.out.println("joinPoint--1");
            return joinPoint.proceed(new String[]{"joinPoint"});
        }catch(RuntimeException e){
            System.out.println("catch");
            return null;
        }
    }

    @Around(value = "execution(public * *(..))")
    public Object myAdvice2(ProceedingJoinPoint joinPoint) throws Throwable {
        try{
            System.out.println("joinPoint--2");
            return joinPoint.proceed();
        }catch(RuntimeException e){
            System.out.println("catch2");
            return null;
        }
    }
}

package aspectj;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"},true);
        MyInterface myInterface= (MyInterface) applicationContext.getBean("MyClass");
        myInterface.objectMethod("Hello");
    }

}

<?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">
    <aop:aspectj-autoproxy />
    <bean id="MyClass" class="aspectj.MyClass"/>
    <bean class="aspectj.MyAdvice"/>
</beans>

xml的文件名如java文件所示,放在src目錄下java

上面的代碼是基本款,運行正常,下面說說特殊狀況spring

MyAdvice裏面有兩個around,前面的先執行,而後調用後面的,至關於前面的around後面的
app

經過給JoinPoint.proceed()傳遞參數,能夠替換掉原來的參數,但是當參數的數量或類型不匹配的時候會報錯,因此簡單點直接調用無參方法便可ide

對於原方法是void但advice中卻又return的狀況,會被直接忽視,因此如代碼所建,void方法也return了spa

更多的功能能夠調用JoinPoint的方法來實現代理

另外若是MyClass實現了多個接口,則獲得的類也實現了那些接口code

若是MyClass繼承了別的類,獲得的代理類不會繼承那個內,這也意味着獲得的確定再也不是MyClass了xml

相關文章
相關標籤/搜索