當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring框架基于AspectJ的AOP开发规范和步骤
生活随笔
收集整理的這篇文章主要介紹了
Spring框架基于AspectJ的AOP开发规范和步骤
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
AOP和動態代理的關系:
AOP術語:
需要新增的到業務代碼中的功能(在目標對象那里叫橫切關注點,在切面類中叫通知)
封裝了增強方法(橫向關注點)的類
切面類中的每一個增強的方法叫做通知,通知通過切入點表達式作用于連接點上
所抽取出來的代碼要作用的對象
切面要作用到目標對象的具體位置,只能是四個位置,方法執行前,方法執行后,異常捕獲后,finilly后.
AOP的切面類通過切入點找到對應的連接點
大白話就是把所有需要增強的方法放在一個類里,該類就是切面類.切面類包含了通知,通知就是需要增強的方法,aop通過切入點表達式讓通知作用于指定目標方法的連接點上,可能是方法之前連接點,方法之后連接點.
一個切面中應該包含@Aspect,通知,切入點表達式,才能夠作用在連接點上
切入點表達式的寫法:
//第一個 * 代表權限修飾符,返回值
//第二個 * 代表該包下的所有的類
//第三個 * 代表該包下的所有的類的所有方法
//…代表任意的參數列表
//切入到com.sms.spring.aop包下的所有類的所有方法的前面
spring在解析這個切入點表達式之后,執行前置|后置|返回通知時,會將方法的信息封裝在JointPoint這個類中:
public void before(JoinPoint joinpoint) {//joinPoint.getArgs():獲取方法的參數Object[] args = joinpoint.getArgs();String methodName = joinpoint.getSignature().getName();}公共切入點寫法:@Pointcut
@Pointcut(value="execution(* com.sms.spring.aop.*.*(..))")public void test(){}公共切入點的使用:
@Before(value="test()")定義切面作用的優先級:@Order(數字),值越小優先級越高
開發步驟:
①導入jar包,或者直接使用maven導入
需要spring的四個核心jar(core,bean,context,expression)+aopalliance+spring-aop+cglib+spring-aspects+aspectjweaver
②創建spring核心xml文件,并引入aop和context的命名空間
③打開spring的組件掃描和AspectJ動態代理
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 開啟組件掃描 --><context:component-scan base-package="com.sms.spring.aop"></context:component-scan><!-- 開啟Asceptj的動態代理功能 --><aop:aspectj-autoproxy /> </beans>④把目標類交給spring管理
給目標類添加@Component注解
⑤把包含增強方法的切面類交給Spring管理并標識 這是個切面類
給切面類添加@Component注解和@Aspect注解
⑥在切面類中寫增強方法,并給方法加上前置|后置|返回|異常 通知,編寫切入點表達式,將該通知(增強方法)作用到連接點
@Before(value = "execution(* com.sms.spring.aop.*.*(..)")public void before(JoinPoint joinpoint) {//joinPoint.getArgs():獲取方法的參數 }⑦使用Spring創建代理對象
其中必須得到接口對象,而非實現類對象,因為代理對象和實現類對象實現共同的接口.
ApplicationContext ac= new ClassPathXmlApplicationContext("aop.xml"); MathI mathI = context.getBean("mathImpl", MathI.class);⑧使用該代理對象調用方法:方法被增強
ApplicationContext ac= new ClassPathXmlApplicationContext("aop.xml"); MathI mathI = context.getBean("mathImpl", MathI.class); mathI.method(); 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Spring框架基于AspectJ的AOP开发规范和步骤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse旧版本Luna SR2(版
- 下一篇: Spring框架关于事务处理的API和使