目錄
一、AOP開發中的相關術語
1. Joinpoint(連接點) -- 所謂連接點是指那些被攔截到的點。在spring中,這些點指的是方法,因爲spring只支持方法類型的連接點
2. Pointcut(切入點) -- 所謂切入點是指我們要對哪些Joinpoint進行攔截的定義
3. Advice(通知/增強) -- 所謂通知是指攔截到Joinpoint之後所要做的事情就是通知.通知分爲前置通知,後置通知,異常通知,最終通知,環繞通知(切面要完成的功能)
4. Introduction(引介) -- 引介是一種特殊的通知在不修改類代碼的前提下,Introduction可以在運行期爲類動態地添加一些方法或Field
5. Target(目標對象) -- 代理的目標對象
6. Weaving(織入) -- 是指把增強應用到目標對象來創建新的代理對象的過程
7. Proxy(代理) -- 一個類被AOP織入增強後,就產生一個結果代理類
8. Aspect(切面) -- 是切入點和通知的結合,以後自己來編寫和配置的
二、spring-aop編程
導入spring的傳統AOP開發包
spring-aop-4.2.4.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar
aspectJ的開發包
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aspects-4.2.4.RELEASE.jar
三、spring配置
配置頭文件:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 1 創建目標類 -->
<bean id="userServiceId" class="spring_aop3.UserServiceImpl"></bean>
<!-- 2 創建切面類(通知) -->
<bean id="myAspectId" class="spring_aop3.MyAdvice"></bean>
<!-- 3 aop編程
3.1 導入命名空間
3.2 使用<aop:config>進行配置
proxy-target-class="true" 聲明時使用cglib代理
<aop:pointcut> 切入點 ,從目標對象獲得具體方法
<aop:advisor> 特殊的切面,只有一個通知 和 一個切入點
advice-ref 通知引用
pointcut-ref 切入點引用
3.3 切入點表達式
execution(* com.qf.c_spring_aop.*.*(..))
選擇方法 返回值任意 包 類名任意 方法名任意 參數任意
-->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.qf.c_spring_aop.*.*(..))" id="myPointCut"/>
<aop:advisor advice-ref="advice" pointcut-ref="myPointCut"/>
</aop:config>
</beans>
通知類寫法:
public class MyAdvice implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation invoke) throws Throwable {
Object proceed = null;
try {
System.out.println("前置通知");
proceed = invoke.proceed();
System.out.println("後置通知");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proceed;
}
}
測試類:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring_aop3/applicationContext.xml")
public class TestAOP {
@Autowired
private UserService UserService;
@Test
public void run() {
UserService.delete();
}
}