1.定義:AOP:Aspect Oriented Programming 面向切面程式設計; 在運作時動态的将代碼切入到指定的點,方法位置上,可以随意添加和删除,不對源代碼産生影響,具有解耦的作用;
2.主要作用:方法執行前,執行後需要記錄日志,或者執行前需要驗證操作權限之類的可以動态的切入,而不用重複的去實作,
3.Aspect 中使用到的注解:
Join Point:表示在程式中明确定義的執行點,典型的Join point包括方法調用,對類成員的通路以及異常處理程式塊的執行,他自身還可以嵌套其他Join Point;
PointCut:事件切入點:表示一組Join Point,把事件發生的地點進行了規律性的總結,通過通配,正規表達式等方式集中起來,定義了相應的advice(事件)要發生的地方;正規表達式 (com.example.service.*,即所有在 service 包下面的方法);
Advice:advice定義了在Point Cut裡面定義的程式點具體要做的操作,他通過@before,@after 和@around 來差別是在每個join Point 之前,之後還是代替執行的代碼;
4.Aop中所用的表達式
其中 execution是用的最多的,其格式為:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
returning type pattern,name pattern, and parameters pattern是必須的.
ret-type-pattern:可以為*表示任何傳回值,全路徑的類名等.
name-pattern:指定方法名,*代表是以,set*,代表以set開頭的所有方法.
parameters pattern:指定方法參數(聲明的類型),(..)代表所有參數,(*)代表一個參數,(*,String)代表第一個參數為任何值,第二個為String類型.
(1)定義在service包裡的任意方法的執行:execution(* com.zhou.service.*.*(..))
(2)定義在service包和所有子包裡的任意類的任意方法的執行:execution(* com.zhou.service..*.*(..))
(3)AccountService 接口的任意方法的執行:execution(* com.zhou.service.AccountService.*(..))
5.簡單的demo,方法之前執行before:
需要引入的包:
org.aspectj
aspectjrt
1.8.10
org.aspectj
aspectjweaver
1.8.10
org.aspectj
aspectjtools
1.8.10
cglib
cglib
2.2
org.springframework
spring-aop
4.3.11.RELEASE
org.springframework
spring-context
4.3.10.RELEASE
在spring xml中需要配置:
定義簡單的注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
public String description() default "init";
}
注解切入點:有兩種方式,一種是直接在代碼中寫,另一種就是在xml中配置;
@Aspect
public class LogIntecept {
public void logPoint(){
}
@Before(value = "execution(* com.zhou.module..*.*(..))")
public void methodBeforeLog(){
System.out.println("method BeforeLog()");
}
}
或者是這樣:
import com.zhou.annotation.LogAnnotation;
public interface TaskBO {
@LogAnnotation(description = "recieveTask")
public void recieveTask();
}
public class TaskBOImpl implements TaskBO {
public void recieveTask() {
System.out.println("do something()");
}
}
以上基本上級就是簡單的aop 代碼:
在main中測試下:
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
TaskBO taskBO = (TaskBO) context.getBean("taskBO");
taskBO.recieveTask();
}
}
輸出:
