生活随笔
收集整理的這篇文章主要介紹了
注解方式实现aop
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
aop注解實現
- spring配置文件
- 目標接口,目標實現類,切面類 注解寫法
- 使用spring-test測試
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
: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"
><!-- spring 組件掃描
--><context
:component
-scan base
-package="com.lovely.aop.anno"/><!-- aop 自動代理測試
--><aop
:aspectj
-autoproxy
/></beans
>
目標接口,目標實現類,切面類 注解寫法
package com
.lovely
.aop
.anno
;public interface TargetInterface {public abstract void save();
}
package com
.lovely
.aop
.anno
;import org
.springframework
.stereotype
.Component
;@Component("target")
public class Target implements TargetInterface {public void save() {System
.out
.println("save running about aop...");}
}
package com
.lovely
.aop
.anno
;import org
.aspectj
.lang
.ProceedingJoinPoint
;
import org
.aspectj
.lang
.annotation
.*
;
import org
.springframework
.stereotype
.Component
;
@Component("myAspect")
@Aspect
public class MyAspect {@Before(value
= "execution(* com.lovely.aop.anno.*.*(..))")public void before() {System
.out
.println("前置增強...");}public void afterReturning() {System
.out
.println("后置增強...");}@Around("MyAspect.myPoint()")public Object
around(ProceedingJoinPoint process
) {System
.out
.println("環繞通知前...");Object obj
= null
;try {obj
= process
.proceed();} catch (Throwable throwable
) {throwable
.printStackTrace();}System
.out
.println("環繞通知后...");return obj
;}public void afterThrowing() {System
.out
.println("異常拉...");}@After("myPoint()")public void after() {System
.out
.println("最終通知...");}@Pointcut("execution(* com.lovely.aop.anno.Target.*(..))")public void myPoint() {}}
使用spring-test測試
import com
.lovely
.aop
.anno
.TargetInterface
;
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:applicationContextAnno.xml")
public class AopAnnotationTest {@Autowiredprivate TargetInterface target
;@Testpublic void test1() {target
.save();}}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的注解方式实现aop的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。