歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring AOP的注解實例

Spring AOP的注解實例

日期:2017/3/1 9:20:52   编辑:Linux編程

上一篇寫了Spring AOP 的兩種代理,這裡開始AOP的實現了,個人喜歡用注解方式,原因是相對於XML方式注解方式更靈活,更強大,更可擴展。所以XML方式的AOP實現就被我拋棄了。

實現Spring AOP需要導入四個包,這裡用maven引入jar包,顏色標注處的jar包,上一篇已經介紹了

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.1_3</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

在applicationContext-mvc.xml(或spring-mvc.xml)中加入下面兩句話,意思是:聲明XML Schema 實例

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

然後開啟@AspectJ注解

在applicationContext-mvc.xml配置如下:

<!-- 啟動對@AspectJ注解的支持 -->
<!-- proxy-target-class等於true是強制使用cglib代理,proxy-target-class默認是false,如果你的類實現了接口 就走JDK代理,如果沒有走cglib代理 -->
<!-- 注:對於單利模式建議使用cglib代理,雖然JDK動態代理比cglib代理速度快,但性能不如cglib -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:annotation-config />
<bean id="interceptor" class="com.gcx.common.Interceptor"/>

其中要注意的是這兩個不能少,在applicationContext-mvc.xml文件中開始時指定

<mvc:annotation-driven />
<!-- 激活組件掃描功能,在包com.gcx及其子包下面自動掃描通過注解配置的組件 -->
<context:component-scan base-package="com.gcx" />

下面開始定義切面,先了解下其基本知識要點

* 連接點(Joinpoint) :程序執行過程中的某一行為(方法),例如,UserService.get()的調用或者UserService.delete()拋出異常等行為。
* 通知(Advice) :“切面”對於某個“連接點”所產生的動作,例如,TestAspect中對com.spring.service包下所有類的方法進行日志記錄的動作就是一個Advice。其中,一個“切面”可以包含多個“Advice”,例如ServiceAspect。
* 切入點(Pointcut) :匹配連接點的斷言,在AOP中通知和一個切入點表達式關聯。例如,TestAspect中的所有通知所關注的連接點,都由切入點表達式execution(* com.spring.service.impl..*.*(..))來決定。
* 目標對象(Target Object) :被一個或者多個切面所通知的對象。例如,AServcieImpl和BServiceImpl,在實際運行時,Spring AOP采用代理實現,實際AOP操作的是TargetObject的代理對象。
* AOP代理(AOP Proxy) :在Spring AOP中有兩種代理方式,JDK動態代理和CGLIB代理。默認情況下,TargetObject實現了接口時,則采用JDK動態代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。強制使用CGLIB代理需要將 <aop:config>的 proxy-target-class屬性設為true 。

通知(Advice)類型

*前置通知(Before advice) :在某連接點(JoinPoint)之前執行的通知,但這個通知不能阻止連接點前的執行。

*後通知(After advice) :當某連接點退出的時候執行的通知(不論是正常返回還是異常退出)。

*返回後通知(After return advice) :在某連接點正常完成後執行的通知,不包括拋出異常的情況。

*環繞通知(Around advice) :包圍一個連接點的通知,類似Web中Servlet規范中的Filter的doFilter方法。可以在方法的調用前後完成自定義的行為,也可以選擇不執行。

*拋出異常後通知(After throwing advice) : 在方法拋出異常退出時執行的通知。

定義一個接口,並編寫實現類:

public interface UserService {
public void addUser(String userName, String password);
}

@Service("userService")
public class UserServiceImpl implements UserService {

@Override
public void addUser(String userName, String password) {
System.out.println("--------------User addUser-------------");
}


}

定義切面類

@Aspect//定義切面
@Component//聲明這是一個組件
public class Interceptor {

private final static Log log = LogFactory.getLog(Interceptor.class);

/**
* 這句話是方法切入點
* 1 execution (* com.wangku.spring.service.impl..*.*(..))
* 2 execution : 表示執行
* 3 第一個*號 : 表示返回值類型, *可以是任意類型
* 4 com.spring.service.impl : 代表掃描的包
* 5 .. : 代表其底下的子包也進行攔截
* 6 第二個*號 : 代表對哪個類進行攔截,*代表所有類
* 7 第三個*號 : 代表方法 *代表任意方法
* 8 (..) : 代表方法的參數有無都可以
*/
//配置切入點,該方法無方法體,主要為方便同類中其他方法使用此處配置的切入點
@Pointcut("execution (* com.gcx.service.impl..*.*(..))")
private void aspect() {
System.out.println("============進入aspect方法==============");
}

//配置環繞通知,使用在方法aspect()上注冊的切入點
@Around("aspect()")
public void around(JoinPoint joinPoint){
long start = System.currentTimeMillis();
try {
((ProceedingJoinPoint) joinPoint).proceed();
long end = System.currentTimeMillis();
if(log.isInfoEnabled()){
log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");//這裡順便記錄下執行速度,可以作為監控
}
} catch (Throwable e) {
long end = System.currentTimeMillis();
if(log.isInfoEnabled()){
log.info("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());
}
}
}
//前置通知等可以沒有JoinPoint參數
@Before("aspect()")
public void doBefore(JoinPoint joinPoint) {
System.out.println("==========執行前置通知===============");
if(log.isInfoEnabled()){
log.info("before " + joinPoint);
}
}
//配置後置通知,使用在方法aspect()上注冊的切入點
@After("aspect()")
public void doAfter(JoinPoint joinPoint) {
System.out.println("===========執行後置通知==============");
if(log.isInfoEnabled()){
log.info("after " + joinPoint);
}
}
//配置後置返回通知,使用在方法aspect()上注冊的切入點
@AfterReturning("aspect()")
public void afterReturn(JoinPoint joinPoint){

System.out.println("===========執行後置返回通知==============");
if(log.isInfoEnabled()){
log.info("afterReturn " + joinPoint);
}
}
//配置拋出異常後通知,使用在方法aspect()上注冊的切入點
@AfterThrowing(pointcut="aspect()", throwing="ex")
public void afterThrow(JoinPoint joinPoint, Exception ex){
if(log.isInfoEnabled()){
log.info("afterThrow " + joinPoint + "\t" + ex.getMessage());
}
}
}
測試類


@Test
public void testAOP1(){
//啟動Spring容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext-mvc.xml","classpath:applicationContext-dataSource.xml"});
UserService userService = (UserService) ctx.getBean("userService");
userService.addUser("zhangsan", "123456");
}

效果圖:

OK!!簡單的spring AOP實現了,在這基礎上可以做下AOP的簡單日志管理了。我的習慣是在後置通知裡添加日志的邏輯代碼。但這這種方式還不是最靈活的,下一篇做下spring AOP 的自定義注解實現日志管理。

Spring AOP進行日志記錄 http://www.linuxidc.com/Linux/2015-11/124731.htm

使用Spring AOP進行性能監控 http://www.linuxidc.com/Linux/2012-07/64681.htm

利用Spring AOP 更新Memcached 緩存策略的實現 http://www.linuxidc.com/Linux/2012-03/56503.htm

Spring AOP的兩種代理 http://www.linuxidc.com/Linux/2015-11/125017.htm

Copyright © Linux教程網 All Rights Reserved