spring基於aspectj的AOP配置 aop:aspectj-autoproxy proxy-target-class="true"
阿新 • • 發佈:2018-12-11
精通Spring4.x--企業應用開發實戰
[email protected]("@annotation()")切點函式詳解
程式碼實現的目標是為NaugthyWaiter類的greetTo()方法實現後置增強,其中greetTo()方法被@NeedTest註解標註。增強類為TestAspect。
增強類:
@Aspect @Component public class TestAspect { @AfterReturning("@annotation(com.smart.anno.NeedTest)") public void needTestFun() { System.out.println("needTestFun() executed!"); } }
目標類:
//@Component public class NaughtyWaiter implements Waiter { @NeedTest public void greetTo(String name) { System.out.println("NaughtyWaiter: greet to " + name + "..."); } public void serveT0(String name) { } public void joke(String clientName, int times) { } }
測試類:
public class PointcutFunTest { @Test public void testFun() { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/smart/aspectj/fun/beans.xml"); Object obj = ctx.getBean("naughtyWaiter"); System.out.println(obj.getClass().getName()); // NaughtyWaiter naughtyWaiter = (NaughtyWaiter) ctx.getBean("naughtyWaiter"); // naughtyWaiter.greetTo("Tom"); // naughtyWaiter.serveT0("Mike"); // naughtyWaiter.joke("Lisa", 3); } }
碰到的問題是<aop:aspectj-autoproxy/> 其中<aop:aspectj-autoproxy/>有一個 proxy-target-class屬性,預設為false,表示使用JDK動態代理技術織入增強;當配置為<aop:aspectj-autoproxy proxy-target-class="true"/>時,表示使用CGLIB動態代理技術織入增強。不過即使proxy-target-class設定為false,如果目標類沒有宣告介面,則Spring將自動使用CGLIB動態代理。
:
1:
<?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"
xmlns:context="http://www.springframework.org/schema/context"
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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.smart"/>
</beans>
應為NaughtyWaiter實現了Waiter介面,使用JDK動態代理,這種配置方式得到的bean是一個com.sun.proxy.$Proxy12,然後後面紅框裡的程式碼就會報錯了:
然後新增 proxy-target-class="true" 屬性,表示使用CGLIB動態代理織入增強
2:
<?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"
xmlns:context="http://www.springframework.org/schema/context"
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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="com.smart"/>
</beans>
問題解決: