天天看點

Spring整理12 -- 面對切面(AOP)2 -- 配置檔案的方式實作AOP

上面我們使用注解配置,注解配置使用很友善也很快速,但它不夠靈活,不好維護。下面我們将使用配置檔案來建立AOP。

我們還是基于上面的例子,使用配置檔案,我們隻需修改上面的SecurityHandler.java和applicationContext.xml,代碼如下:

SecurityHandler.java

public class SecurityHandler { 

    private void checkSecurity() {

       System.out.println("------checkSecurity()------");

    }

}

applicationContext.xml

    <bean id="securityHandler"class="spring.SecurityHandler"/>          

    <bean id="userManager" class="spring.UserManagerImpl"/>

    <aop:config>

       <aop:aspect id="security" ref="securityHandler">

           <aop:pointcut id="allAddMethod"

expression="execution(*spring.UserManagerImpl.add*(..))"

/>

           <aop:before method="checkSecurity"

pointcut-ref="allAddMethod"/>

       </aop:aspect>

    </aop:config>

從上面代碼,我們會發現一個問題,如何在切面中如何傳遞參數呢?

我們切面的參數都封裝在JoinPoint類中,得到參數使用joinPoint.getArgs()傳回一個數組,得到方法名使用joinPoint.getSignature().getName()。

測試一下,修改SecurityHandler.java

public class SecurityHandler {

    private void checkSecurity(JoinPoint joinPoint) {

       Object[] args = joinPoint.getArgs();

       for (int i=0; i<args.length; i++) {

           System.out.println(args[i]);

       }

       System.out.println(joinPoint.getSignature().getName());

       System.out.println("----checkSecurity()----");

    }

}