<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java advice是什麼,讓我們一起了解一下?
Advice是在Join Point上執行的一個動作或者通知,一般透過攔截器調用。Spring有兩大核心,IOC和AOP,在模組AOP裏面有個advice。
在Spring-AOP中,增強(Advice)是如何實現的?
按照增強在目標類方法連接點的位置可以將增強劃分爲以下五類:
前置增強 (org.springframework.aop.BeforeAdvice) 表示在目標方法執行前來實施增強。
後置增強 (org.springframework.aop.AfterReturningAdvice)表示在目標方法執行後來實施增強。
環繞增強 (org.aopalliance.intercept.MethodInterceptor)表示在目標方法執行前後同時實施增強。
異常拋出增強 (org.springframework.aop.ThrowsAdvice) 表示在目標方法拋出異常後來實施增強。
引介增強 (org.springframework.aop.introductioninterceptor)表示在目標類中添加一些新的方法和屬性。
實戰操作:Spring中Advice簡單案例
1、配置類
@Configuration//配之類@EnableAspectJAutoProxy//啓用AspectJ自動代理@ComponentScan(basePackages = {"spring01","spring02"}) //basePackages指定掃描的包public class Config {}
2、切面類
@Aspect@Componentpublic class Audience { /** * 相當於訪問相同報下的不同的類,他們擁有相同的包路徑,可以定義一個變量 */ @Pointcut("execution(* spring02.aspect.Performance.perform(..))") public void performance(){ } @Before("performance()") public void silenceCellPhones(){ System.out.println("====表演前將手機調靜音"); } @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、被通知對象實現類
@Component("performance")public class PerformanceImpl implements Performance{ @Override public void perform() { System.out.println("======表演開始====="); }}
5、測試類
@RunWith(SpringJUnit4ClassRunner.class)//啓動測試時創建Spring上下文@ContextConfiguration(classes = {Config.class})//配置檔案對象public class TestClass { @Autowired private Performance performance; @Test public void test(){ performance.perform(); }}