天天看點

Spring AOP了解與使用

如果你想要使用AOP,那麼正面spring架構基本已經會配置了,那麼就不再做詳述;

1. 特點:不改變原有的邏輯代碼的情況下,給系統增加新的功能,如事務控制、異常日志資訊等;

Spring AOP了解與使用

如圖所示,不改變controller和service之間的代碼增加對應的Spring AOP 功能

2. 配置檔案spring-aop.xml檔案,如下主要配置相應的切入類,切入的方法,切入的目的,修改其中的<aop:  befor method="xxx" pointcut="">  ,method 指定切入的方法,pointcut指定切入的包。

<?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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd  
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<bean id="logBean" class="com.tpdog.aspect.LogBean" />
	<aop:config>
		<!-- 通過REF把元件關聯起來 -->
		<aop:aspect ref="logBean">
			<!-- 指定AOP執行方法 -->
			<aop:before method="logController" pointcut="within(com.tpdog.controller..*)" />
		</aop:aspect>
	</aop:config>
</beans> 
           

3. 編寫配置檔案的Bean和相應的method方法,需要切入的包中的類不用改變;

package com.tpdog.aspect;

public class LogBean {

	public void logController() {
		System.out.println(this.getClass() + "AOP注入相關資訊");
	}
}
           
Spring AOP了解與使用

如圖:配置好的切入的類和被切入的包,找到切入類中的方法,執行切入的方法

4.  效果展示:

Spring AOP了解與使用

5. 拓展延伸

用于指定目标元件的方法: executtion(修飾符? 傳回類型 方法名(參數,), 異常抛出)

//比對所有的get方法

executtion(* get*(...))

//比對包下的所有方法

executtion(* com.tpdog..*(..))