• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
seven_hu
博客园    首页    新随笔    联系   管理    订阅  订阅

面向切面编程AOP:基于XML文件的配置

除了使用AspectJ注解声明切面,Spring也支持在bean的配置文件中声明切面,这种声明是通过aop scheme中的XML元素完成的。

首先建立一个类:

package com.sevenhu.AOPTests;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;

import java.util.Arrays;

/**
 * Created by hu on 2016/4/1.
 */
public class AspectDemo1 {
    //前置通知
    @Before("execution(public int com.sevenhu.AOPTests.Calculator.*(int ,int ))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName=joinPoint.getSignature().getName();
        Object[] args=joinPoint.getArgs();
        System.out.println("The method "+methodName+" begins with "+ Arrays.asList(args));
    }
}

配置如下:

       <!--使AspesctJ的注解起作用-->
       <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
       <bean id="aspectDemo1" class="com.sevenhu.AOPTests.AspectDemo1"></bean>
       <aop:config>
              <aop:aspect id="aspect1" ref="aspectDemo1"></aop:aspect>
       </aop:config>

基于XML声明切入点:

       <!--使AspesctJ的注解起作用-->
       <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
       <bean id="aspectDemo1" class="com.sevenhu.AOPTests.AspectDemo1"></bean>
       <aop:config>
              <aop:pointcut id="cutExpression" expression="execution(* *.*(..))"/>
              <aop:aspect id="aspect1" ref="aspectDemo1"></aop:aspect>
       </aop:config>

声明通知的示例代码:

       <!--加入自动扫描的包-->
       <context:component-scan base-package="com.sevenhu.AOPTests"></context:component-scan>
       <!--使AspesctJ的注解起作用-->
       <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
       <bean id="aspectDemo1" class="com.sevenhu.AOPTests.AspectDemo1"></bean>
       <aop:config>
              <aop:pointcut id="cutExpression" expression="execution(* *.*(..))"/>
              <aop:aspect id="aspect1" ref="aspectDemo1">
                     <aop:before method="beforeMethod" pointcut-ref="cutExpression"></aop:before>
              </aop:aspect>
       </aop:config>

  

posted @ 2016-04-01 13:20  seven_hu  阅读(445)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3