544
技術社區[雲棲]
第三章 AOP 基於@Aspect的AOP
在前麵,我們分別使用Pointcut、Advice、Advisor接口來描述切點、增強、切麵。而現在我們使用@Adpect注解來描述。
在下麵的例子中,我們是使用Spring自動掃描和管理Bean。
(https://blog.csdn.net/p_3er/article/details/9239605)
3.6.1一個簡單的例子
@Repository public class UserDaoImpl implements UserDao { public void save() { System.out.println("保存用戶..."); } public void delete() { System.out.println("刪除用戶..."); } }
b、通過一個POJO使用@AspectJ管理切麵
/* * 通過@Aspect把這個類標識管理一些切麵 */ @Aspect @Component public class FirstAspect { /* * 定義切點及增強類型 */ @Before("execution(* save(..))") public void before(){ System.out.println("我是前置增強..."); } }
c、配置
配置的時候要引入aop命名空間及打開@Aspect切麵驅動器
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <!— 驅動器自動為Spring容器中那些匹配@AspectJ切麵的Bean創建代理,完成切麵積入 --> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserDao userDao = (UserDao) context.getBean("userDaoImpl"); userDao.save(); userDao.delete();
e、結果
我是前置增強... 保存用戶... 刪除用戶...
3.6.2增強類型及其使用
@Before前置增強
@Before(value= "切入點表達式或命名切入點",argNames = "指定命名切入點方法參數列表參數名字,可以有多個用“,”分隔")
3.6.1中的增強使用:@Before(value="execution(*save(..))")是缺省了value,直接鍵入值。
a、目標類
@Service public class UserService { public void say(String name){ System.out.println("service say:"+name); } public void run(String way){ System.out.println("service run:"+way); } }
b、通過一個POJO使用@AspectJ管理切麵
@Aspect @Component public class BeforAspectj { /* *單獨配置切點。給切點命名。 */ @Pointcut(value="execution(* say(..)) && args(param)",argNames="param") public void beforePointcut(String param){ } @Before(value="beforePointcut(s)",argNames="s") public void beforeAdvice(String s){ System.out.println("beforeAdvice:"+s); } }
@Aspect @Component public class BeforAspectj { @Before(value="execution(* say(..)) && args(s)",argNames="s") public void beforeAdvice(String s){ System.out.println("beforeAdvice:"+s); } }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService"); service.say("zhangsan"); service.run("street");
e、結果
beforeAdvice:zhangsan service say:zhangsan service run:street
@AfterReturning後置增強
@AfterReturning(
value="切入點表達式或命名切入點",
pointcut="切入點表達式或命名切入點",
argNames="參數列表參數名",
returning="目標對象的返回值")
pointcut與value是一樣的。如果使用pointcut來聲明,那麼前麵聲明的value就沒用了。
@Service public class UserService { public void say(String name){ System.out.println("service say:"+name); } public void run(String way){ System.out.println("service run:"+way); } public String getName(String name){ System.out.println("service getName:"+name); return "MR"+name; } }
b、通過一個POJO使用@AspectJ管理切麵
@Aspect @Component public class AfterReturningAspectj { /* * 即獲取返回值,又獲取傳入的參數 */ @AfterReturning( value="execution(* cn.framelife.spring..*.getName(..)) && args(sname)", returning="name", argNames="name,sname") public void afterGetNameAdvice(Object object,String sname){ System.out.println("afterGetNameAdvice:"+ (String)object+"--"+sname); } /* * 隻要增強,返回值和參數都不理會 */ @AfterReturning(value="execution(* cn.framelife.spring..*.run(..))") public void afterRunAdvice(){ System.out.println("afterRunAdvice"); } }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService "); service.getName("zhangsan"); service.run("street");
e、結果
servicegetName:zhangsan afterGetNameAdvice:MRzhangsan--zhangsan servicerun:steet afterRunAdvice
@AfterThrowing異常拋出增強、@After Final增強
@AfterThrowing(
value="切入點表達式或命名切入點",
pointcut="切入點表達式或命名切入點",
argNames="參數列表參數名",
throwing="異常對應參數名")
@After( value="切入點表達式或命名切入點",argNames="參數列表參數名")
@After不管是拋出異常或者是正常退出,該增強都會執行。相當於try-catch-final裏的final代碼塊。
a、目標類
@Service public class UserService { public void tryThrow(){ System.out.println("service tryThrow"); throw new RuntimeException("i am a runtime exception"); } }
b、通過一個POJO使用@AspectJ管理切麵
@Aspect @Component public class ThrowAspectj { @AfterThrowing(value="execution(* cn.framelife.spring..tryThrow(..))", throwing="exception", argNames="exception") public void afterThrowAdvisor(Exception exception){ System.out.println("afterThrowAdvisor:"+exception.getMessage()); } @After(value="execution(* cn.framelife.spring..tryThrow(..))") public void finalThrowAdvisor(){ System.out.println("finalThrowAdvisor"); } }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService "); service.tryThrow();
e、結果
servicetryThrow afterThrowAdvisor:iam a runtime exception finalThrowAdvisor Exceptionin thread "main" java.lang.RuntimeException:i am a runtime exception
@Around環繞增強
@Around( value="切入點表達式或命名切入點",argNames="參數列表參數名")
a、目標類
@Service public class UserService { public void round(){ System.out.println("service round"); } public void run(String way){ System.out.println("service run:"+way); } public String getName(String name){ System.out.println("service getName:"+name); return "MR"+name; } }
b、通過一個POJO使用@AspectJ管理切麵
@Aspect @Component public class AroundAspect { @Around(value="execution(* cn.framelife.spring..round(..))") public Object aroundAdvisor(ProceedingJoinPoint point) throws Throwable{ System.out.println("before method"); Object target = point.proceed(); System.out.println("after method"); return target; } }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService"); service.round(); service.run("street");
e、結果
beforemethod serviceround aftermethod servicerun:street afterRunAdvice
@DeclareParents引介增強
@DeclareParents(
value="AspectJ語法類型表達式",
defaultImpl=引入接口的默認實現類)
下麵的例子是Waiter為目標類,然後讓目標類擁有ISeller接口的功能:
a、兩個接口與兩個類
目標類與其接口:
public interface IWaiter { public void service(); }
@Component public class Waiter implements IWaiter { @Override public void service() { System.out.println("service"); } }
運行期織入到目標類的功能類與其接口:
public interface ISeller { public void sell(); }
public class Seller implements ISeller { @Override public void sell() { System.out.println("sell"); } }
@Aspect @Component public class DeclareAspect { /* * value裏麵配置目標類 * defaultImpl是功能類的實現類 */ @DeclareParents( value="cn.framelife.spring.aspectj.Waiter", defaultImpl=Seller.class) private ISeller seller; //使用功能類接口聲明一個對象 }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); IWaiter waiter = (IWaiter) context.getBean("waiter"); waiter.service(); ISeller seller = (ISeller)waiter; seller.sell();
e、結果
service sell
3.6.3切點函數
帶@開頭的函數都是針對注解類的。而不帶@的函數是針對普通類的。
execution()
execution(<修飾符模式>?<返回類型模式><方法名模式>(<參數模式>)<異常模式>?)
除了返回類型模式、方法名模式和參數模式外,其它都是可選的。
1)通過方法簽名定義切點
execution(public* *(..))
匹配所有目標類的public方法,但不匹配SmartSeller和protectedvoid showGoods()方法。第一個*代表返回類型,第二個*代表方法名,而..代表任意入參的方法;
execution(* *To(..))
匹配目標類所有以To為後綴的方法。它匹配NaiveWaiter和NaughtyWaiter的greetTo()和serveTo()方法。第一個*代表返回類型,而*To代表任意以To為後綴的方法;
2)通過類定義切點
execution(*com.baobaotao.Waiter.*(..))
匹配Waiter接口的所有方法,它匹配NaiveWaiter和NaughtyWaiter類的greetTo()和serveTo()方法。第一個*代表返回任意類型,com.baobaotao.Waiter.*代表Waiter接口中的所有方法;
execution(*com.baobaotao.Waiter+.*(..))
匹配Waiter接口及其所有實現類的方法,它不但匹配NaiveWaiter和NaughtyWaiter類的greetTo()和serveTo()這兩個Waiter接口定義的方法,同時還匹配NaiveWaiter#smile()和NaughtyWaiter#joke()這兩個不在Waiter接口中定義的方法。
3)通過類包定義切點
在類名模式串中,“.*”表示包下的所有類,而“..*”表示包、子孫包下的所有類。
execution(*com.baobaotao.*(..))
匹配com.baobaotao包下所有類的所有方法;
execution(*com.baobaotao..*(..))
匹配com.baobaotao包、子孫包下所有類的所有方法,如com.baobaotao.dao,com.baobaotao.servier以及com.baobaotao.dao.user包下的所有類的所有方法都匹配。“..”出現在類名中時,後麵必須跟“*”,表示包、子孫包下的所有類;
execution(*com..*.*Dao.find*(..))
匹配包名前綴為com的任何包下類名後綴為Dao的方法,方法名必須以find為前綴。如com.baobaotao.UserDao#findByUserId()、com.baobaotao.dao.ForumDao#findById()的方法都匹配切點。
4)通過方法入參定義切點
切點表達式中方法入參部分比較複雜,可以使用“*”和“..”通配符,其中“*”表示任意類型的參數,而“..”表示任意類型參數且參數個數不限。
execution(*joke(String,int)))
匹配joke(String,int)方法,且joke()方法的第一個入參是String,第二個入參是int。它匹配NaughtyWaiter#joke(String,int)方法。如果方法中的入參類型是java.lang包下的類,可以直接使用類名,否則必須使用全限定類名,如joke(java.util.List,int);
execution(*joke(String,*)))
匹配目標類中的joke()方法,該方法第一個入參為String,第二個入參可以是任意類型,如joke(Strings1,String s2)和joke(Strings1,double d2)都匹配,但joke(Strings1,double d2,String s3)則不匹配;
execution(*joke(String,..)))
匹配目標類中的joke()方法,該方法第一個入參為String,後麵可以有任意個入參且入參類型不限,如joke(Strings1)、joke(Strings1,String s2)和joke(Strings1,double d2,String s3)都匹配。
execution(*joke(Object+)))
匹配目標類中的joke()方法,方法擁有一個入參,且入參是Object類型或該類的子類。它匹配joke(Strings1)和joke(Clientc)。如果我們定義的切點是execution(*joke(Object)),則隻匹配joke(Objectobject)而不匹配joke(Stringcc)或joke(Clientc)。
args()
該函數的入參是一個類名,表示目標類的方法入參對象是指定的類(包含子類),切點匹配。它允許類後後使用+通配符後綴,但添加也不添加+效果是一樣的。
例子:
public class User implements Serializable { }
b、目標類
@Service public class UserService { public void say(User user){ System.out.println("say"); } }
c、通過一個POJO使用@AspectJ管理切麵
@Aspect @Component public class BeforAspectj { @Before(value="args(cn.framelife.spring.aspectj.User)") public void beforeAdvice(){ System.out.println("beforeAdvice"); } }
d、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
e、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService"); service.say(new User());
f、結果
beforeAdvice say
within()
通過類的匹配模式串聲明切點。該函數定義的連接點是針對目標類(不能是接口)而言,而不是針對運行時的對象,這與execution()函數相同。Execution()所指定的連接點可以是小到參數,而within()指定的連接點最小隻能是類。
within(cn.framelife.spring.aspectj.UserService)
匹配UserService類下所有的方法。
within(cn.framelife.spring.aspectj.*)
匹配cn.framelife.spring.aspectj包下所的的類,但不包括子孫包。cn.framelife.spring.aspectj.abc.AbcService是不匹配的。
within(cn.framelife.spring.aspectj..*)
匹配cn.framelife.spring.aspectj包及其子孫包下所的的類。
target()與this()
target()函數是通過判斷目標類是否按類型匹配指定類決定連接點是否匹配。
target(cn.framelife.spring.aspectj.UserService)
匹配這UserService類及其子孫類的所有方法。如果UserService是一個接口,那麼會匹配UserService的實現類及實現類的子孫類中的所有的方法。
this()函數是通過判斷代理類是否按類型匹配指定類決定連接點是否匹配。
一般情況下,使用this()和target()定義切點,兩者是等效的:
target(cn.framelife.spring.aspectj.UserService)與this(cn.framelife.spring.aspectj.UserService)是一樣的。無論UserService是一個類還是一個接口。
兩者區別體現在通過引介切麵產生代理對象時。
@annotation()
表示標注了某個自定義注解的方法,使用切麵。
@Retention(value=RetentionPolicy.RUNTIME) @Target(value=ElementType.METHOD) public @interface BeforeAdvisor { boolean value() default false; }
@Aspect @Component public class BeforAspectj { @Before(value="@annotation(cn.framelife.spring.aspectj.annotation.BeforeAdvisor)") public void beforeAdvice(){ System.out.println("beforeAdvice"); } }
c、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
d、目標類
@Service public class UserService { @BeforeAdvisor public void annotation(){ System.out.println("annotation"); } }
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService"); service.annotation();
f、結果
beforeAdvice annotation
@args()
該函數的入參是一個注解類的類名,表示運行時目標類方法的入參對象的類標注了指定的注解。
@Retention(value=RetentionPolicy.RUNTIME) @Target(value=ElementType.TYPE) public @interface UserAnnotation { }
b、切麵管理
@Aspect @Component public class BeforAspectj { @Before(value="@args(cn.framelife.spring.aspectj.annotation.UserAnnotation)") public void beforeAdvice(){ System.out.println("beforeAdvice"); } }
c、實體類(使用上麵定義的注解)
@UserAnnotation public class User implements Serializable { }
d、目標類
@Service public class UserService { public void annotation(){ System.out.println("annotation"); } public void say(User user){ System.out.println("say"); } }
e、配置和3.6.1中一樣
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:p="https://www.springframework.org/schema/p" xmlns:context="https://www.springframework.org/schema/context" xmlns:aop="https://www.springframework.org/schema/aop" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.0.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="cn.framelife.spring"></context:component-scan> <aop:aspectj-autoproxy/>
f、測試
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); UserService service = (UserService) context.getBean("userService"); service.say(new User());
g、結果
beforeAdvice say
@within和@target()
@winthin(A)匹配任意標注了@A的目標類。@target(A)匹配@A的類及子孫類。
@annotation是標注在目標類的方法
@args是標注目標類方法的入參對象的類
@winthin與@target是標注目標類
注意
上麵的函數(特別是args())除了可以指定類名外,還可以指定參數名,將目標對象連接點上的方法入參綁定到增強的方法中。如:@Before中的例子。
3.6.4通配符與邏輯運算符
@Aspect支持3種通配符:
*匹配任意字符,但它隻能匹配上下文中的一個元素
..匹配任意字符,可以匹配上下文中的多個元素,但在表示類時,必須和*聯合使用,而在表示入參時則單獨使用。
+表示按類型匹配指定類及其子孫類,必須跟在類名後麵。如cn.framelife.spring.UserService+表示UserService類及其子類。
函數支持:
支持所有的通配符的函數:execution()、within()
僅支持+通配符的函數:args()、this()、targ()。雖然這三個函數可以支持+通配符,但對於這些函數來說使用和不使用+都是一樣的。
不支持通配符的函數:@args、@within、@target()、@annotation()。也就是所有用於注解上的函數都不支持通配符。
@Aspectj支持的邏輯運算符:
&&與
||或
!非
最後更新:2017-04-03 16:48:31