[TOC]
# 注解方式 AOP
本章節把XML方式配置AOP 改造為注解方式
## 步驟 1 : 先運行,看到效果,再學習
先將完整的 spring 項目(向老師要相關資料),配置運行起來,確認可用之后,再學習做了哪些步驟以達到這樣的效果。
## 步驟 2 : 模仿和排錯
在確保可運行項目能夠正確無誤地運行之后,再嚴格照著教程的步驟,對代碼模仿一遍。
模仿過程難免代碼有出入,導致無法得到期望的運行結果,此時此刻通過比較**正確答案** ( 可運行項目 ) 和自己的代碼,來定位問題所在。
采用這種方式,**學習有效果,排錯有效率**,可以較為明顯地提升學習速度,跨過學習路上的各個檻。
## 步驟 3 : 注解配置業務類
使用@Component("s") 注解ProductService 類
~~~
package com.dodoke.service;
import org.springframework.stereotype.Component;
@Component("s")
public class ProductService {
public void doSomeService() {
System.out.println("doSomeService1");
}
}
~~~
## 步驟 4 : 注解配置切面
@Aspect 注解表示這是一個切面
@Component 表示這是一個bean,由Spring進行管理
@Around(value = "execution(* com.dodoke.service.ProductService.*(..))") 表示對com.dodoke.service.ProductService 這個類中的所有方法進行切面操作。
~~~
package com.dodoke.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggerAspect {
@Around(value = "execution(* com.dodoke.service.ProductService.*(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("start log:" + joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
System.out.println("end log:" + joinPoint.getSignature().getName());
return object;
}
}
~~~
## 步驟 5 : applicationContext.xml
~~~
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.dodoke.pojo" />
<!-- 掃描切面類 -->
<context:component-scan base-package="com.dodoke.aspect"></context:component-scan>
<!-- 掃描業務類 -->
<context:component-scan base-package="com.dodoke.service"></context:component-scan>
<!-- 啟動對AOP的支持,找到被注解了的切面類,進行切面配置 -->
<aop:aspectj-autoproxy />
</beans>
~~~
## 步驟 6 : 運行測試
運行結果:
