天天看点

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..*(..))