天天看點

Spring AOP切面的配置與實作簡述

① 導入依賴jar包

Spring AOP切面的配置與實作簡述
② 在resources檔案夾下的配置spring-aop.xml檔案
Spring AOP切面的配置與實作簡述
③ 編寫背景代碼實作

@Component //聲明是通用注解
@Aspect     //聲明目前類是一個切面元件,必須與<aop:aspectj-autoproxy/>配合使用
public class ProxyAspect {

    @Around("bean(list)")   //切入到list bean對象的全部方法
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {  
        //johnPoint代表被調用目标對象的方法,其封裝了目标對象和調用的方法。
        //可以通過getSignature()來擷取調用的方法資訊
        Signature s = joinPoint.getSignature();
        System.out.println(s);
        
        //添加同步代碼塊
        synchronized (this) {
            //proceed()方法底層封裝了invoke()
            return joinPoint.proceed();
        }       
    }
}
           

編寫測試類

@Test
public void testSpringList() {
    ClassPathXmlApplicationContext ctx = new classPathXmlApplicationContext("spring-aop.xml");
    List<String> list = ctx.getBean("list", List.class);
    list.add("TOM");
    list.add("JERRY");
    System.out.println(list.getClass());    
    System.out.println(list);       
}           

AOP配置簡述,以免遺忘。不足之處,敬請見諒。