java advice是什么,讓我們一起了解一下?
Advice是在Join Point上執(zhí)行的一個動作或者通知,一般通過攔截器調(diào)用。Spring有兩大核心,IOC和AOP,在模塊AOP里面有個advice。
在Spring-AOP中,增強(Advice)是如何實現(xiàn)的?
按照增強在目標類方法連接點的位置可以將增強劃分為以下五類:
前置增強 (org.springframework.aop.BeforeAdvice) 表示在目標方法執(zhí)行前來實施增強。
后置增強 (org.springframework.aop.AfterReturningAdvice)表示在目標方法執(zhí)行后來實施增強。
環(huán)繞增強 (org.aopalliance.intercept.MethodInterceptor)表示在目標方法執(zhí)行前后同時實施增強。
異常拋出增強 (org.springframework.aop.ThrowsAdvice) 表示在目標方法拋出異常后來實施增強。
引介增強 (org.springframework.aop.introductioninterceptor)表示在目標類中添加一些新的方法和屬性。
實戰(zhàn)操作:Spring中Advice簡單案例
1、配置類
@Configuration//配之類 @EnableAspectJAutoProxy//啟用AspectJ自動代理 @ComponentScan(basePackages?=?{"spring01","spring02"})?//basePackages指定掃描的包 public?class?Config?{ }
2、切面類
@Aspect @Component public?class?Audience?{ ????/** ?????*?相當于訪問相同報下的不同的類,他們擁有相同的包路徑,可以定義一個變量 ?????*/ ????@Pointcut("execution(*?spring02.aspect.Performance.perform(..))") ????public?void?performance(){ ????} ? ????@Before("performance()") ????public?void?silenceCellPhones(){ ????????System.out.println("====表演前將手機調(diào)靜音"); ????} ? ????@Before("performance()") ????public?void?takeSeats(){ ????????System.out.println("====表演前就做"); ????} ? ????@AfterReturning("performance()") ????public?void?applause(){ ????????System.out.println("====表演后鼓掌"); ????} ? ????@AfterThrowing("performance()") ????public?void?demandRefund(){ ????????System.out.println("====表演失敗時退款"); ????} ????@Around("performance()") ????public?void??watchPerformance(ProceedingJoinPoint?point){ ????????try?{ ????????????System.out.println("====觀看前1"); ????????????point.proceed(); ????????????System.out.println("====觀看后2"); ????????}?catch?(Throwable?throwable)?{ ????????????throwable.printStackTrace(); ????????} ????} }
3、被通知對象接口
public?interface?Performance?{ void?perform(); }
4、被通知對象實現(xiàn)類
@Component("performance") public?class?PerformanceImpl?implements?Performance{ ????@Override ????public?void?perform()?{ ????????System.out.println("======表演開始====="); ????} }
5、測試類
@RunWith(SpringJUnit4ClassRunner.class)//啟動測試時創(chuàng)建Spring上下文 @ContextConfiguration(classes?=?{Config.class})//配置文件對象 public?class?TestClass?{ ????@Autowired ????private?Performance?performance; ????@Test ????public?void?test(){ ????????performance.perform(); ????} }
以上就是小編今天的分享了,希望可以幫助到大家。