# AOP實現方式三-使用注解實現 ###### tags: `Spring-AOP` 1.在類中加入注解,成為切面以及將方法寫為切入點 ```java= @Aspect //標注這個類是個切面 public class AnnotationPointCut { @Before("execution(* com.kuang.service.UserServiceImpl.*(..))") public void before(){ System.out.println("===方法執行前==="); } @After("execution(* com.kuang.service.UserServiceImpl.*(..))") public void after(){ System.out.println("==方法執行後=="); } //在環繞增強中,我們可以給定一個參數,代表我們要獲取處理切入的點 @Around("execution(* com.kuang.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable { System.out.println("環繞前"); Signature signature = jp.getSignature();//獲得簽名 System.out.println("signature:" + signature); //執行方法 Object proceed = jp.proceed(); System.out.println("環繞後"); System.out.println(proceed); } } ``` **注意:** 切入方法與其他類中的方法同名,引用時要注意  2.在配置中,就僅需要用<aop:aspectj-autoproxy/>來自動配置切面 ```xml= <!--方式三--> <bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/> <!--開啟注解支持 JDK(默認) cglib--> <aop:aspectj-autoproxy/> ``` 3.測試 ```java= public class MyTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //注意點:動態代理代理的是接口 UserService userService = (UserService) context.getBean("userService"); userService.add(); } } ``` 4.結果 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up