假如有以下service,他的功能很簡單,打印輸入的參數(shù)并返回參數(shù)。
@Servicepublic class SimpleService { public String getName(String name) { System.out.println(get name is: + name); return name; }} @Component@aspectpublic class LogAspect { // 定義切點(diǎn) @Pointcut(within(com.ydoing.service..*)) // @Pointcut(execution(* com.ydoing.service.*.*(..))) public void pointCut() { } } // 定義Before增強(qiáng)處理 // 在目標(biāo)方法調(diào)用之前執(zhí)行增強(qiáng)處理 @Before(pointCut()) public void before(JoinPoint jp) { // 獲取連接點(diǎn)傳入?yún)?shù) // Object args = jp.getArgs(); System.out.println(Before增強(qiáng)處理--execute before target method call); } 測試輸出:
Before增強(qiáng)處理--execute before target method callget name is: Bob // 在目標(biāo)方法調(diào)用之后執(zhí)行增強(qiáng)處理 @AfterReturning(pointcut = pointCut(), returning = ret) public void afterReturning(JoinPoint jp, Object ret) { System.out.println(AfterReturnin增強(qiáng)處理--execute after target method call, return value is : + ret); }測試輸出:
get name is: BobAfterReturnin增強(qiáng)處理--execute after target method call, return value is :Bob @Around(pointCut()) public void around(ProceedingJoinPoint jp) { System.out.println(Around增強(qiáng)--around start...); Object[] args = jp.getArgs(); // 修改目標(biāo)方法傳入的參數(shù) args[0] = around_add_ + args[0]; try { System.out.println(修改傳入?yún)?shù)后執(zhí)行輸出:); jp.proceed(args); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Around增強(qiáng)--around end); }輸出:
Around增強(qiáng)--around start...修改傳入?yún)?shù)后執(zhí)行輸出:get name is: around_add_BobAround增強(qiáng)--around end // 無論是否發(fā)生異常都會(huì) 處理 @After(pointCut()) public void after() { System.out.println(After增強(qiáng)--always do no matter what happen); }輸出:
get name is: BobAfter增強(qiáng)--always do no matter what happen @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 聚集很多互聯(lián)網(wǎng)精英,技術(shù)總監(jiān),架構(gòu)師,項(xiàng)目經(jīng)理!開源技術(shù)研究,歡迎業(yè)內(nèi)人士,大牛及新手有志于從事IT行業(yè)人員進(jìn)入!
新聞熱點(diǎn)
疑難解答
圖片精選