Spring中AOP執行個體詳解,SpringAOP執行個體詳解
Spring中AOP執行個體詳解
需要增強服務
假如有以下service,他的功能很簡單,列印輸入的參數並返回參數。
@Servicepublic class SimpleService { public String getName(String name) { System.out.println(get name is: + name); return name; }}
定義切面和切點
@Component@Aspectpublic class LogAspect { // 定義切點 @Pointcut(within(com.ydoing.service..*)) // @Pointcut(execution(* com.ydoing.service.*.*(..))) public void pointCut() { } }
Before增強處理
// 定義Before增強處理 // 在目標方法調用之前執行增強處理 @Before(pointCut()) public void before(JoinPoint jp) { // 擷取連接點傳入參數 // Object args = jp.getArgs(); System.out.println(Before增強處理--execute before target method call); }
測試輸出:
Before增強處理--execute before target method callget name is: Bob
AfterReturning增強
// 在目標方法調用之後執行增強處理 @AfterReturning(pointcut = pointCut(), returning = ret) public void afterReturning(JoinPoint jp, Object ret) { System.out.println(AfterReturnin增強處理--execute after target method call, return value is : + ret); }
測試輸出:
get name is: BobAfterReturnin增強處理--execute after target method call, return value is :Bob
Around增強
@Around(pointCut()) public void around(ProceedingJoinPoint jp) { System.out.println(Around增強--around start...); Object[] args = jp.getArgs(); // 修改目標方法傳入的參數 args[0] = around_add_ + args[0]; try { System.out.println(修改傳入參數後執行輸出:); jp.proceed(args); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Around增強--around end); }
輸出:
Around增強--around start...修改傳入參數後執行輸出:get name is: around_add_BobAround增強--around end
After增強
// 無論是否發生異常都會 處理 @After(pointCut()) public void after() { System.out.println(After增強--always do no matter what happen); }
輸出:
get name is: BobAfter增強--always do no matter what happen
AfterThrowing增強
@AfterThrowing(pointcut = pointCut(), throwing = ex) public void afterThrowing(JoinPoint jp, Throwable ex) { System.out.println(error is: + ex); }
這裡沒拋異常,就沒有輸出了
測試代碼如下
@Configuration@EnableAspectJAutoProxy@ComponentScan(basePackages = com.ydoing.service,com.ydoing.aspect)public class AppConfig { public static void main(String[] args) { @SuppressWarnings(resource) ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); SimpleService service = ctx.getBean(SimpleService.class); service.getName(Bob); }}
原文地址:http://www.bkjia.com/Javabc/1077751.html
QQ群290551701 聚集很多互連網精英,技術總監,架構師,專案經理!開源技術研究,歡迎業內人士,大牛及新手有志於從事IT行業人員進入!