spring aop切面配置实现日志功能

最近在用SSM框架写一个项目,需要记录客户操作写入数据库,上网上查了一下,发现使用spring aop就很简单,目标是写入数据库,今天只是实现了切面,检查出操作的方法
实体类那些东西就不写了,直接放入关键的几个类吧:
切面类:

package org.jit.sose.interceptor;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class Aspect {
    //前置通知
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知");
        System.out.println("目标类:"+joinPoint.getTarget());
        System.out.println("目标方法:"+joinPoint.getSignature().getName());
    }

    //后置通知
    public void afterReturn(JoinPoint joinPoint){
        System.out.println("后置通知");
        System.out.println("被植入增强的处理的目标方法:"+joinPoint.getTarget());
    }
    //环绕通知
    public Object around(ProceedingJoinPoint pJoinPoint) throws Throwable{
        System.out.println("环绕开始:执行目标方法之前,模拟开始事务");
        Object obj=pJoinPoint.proceed();
        System.out.println("环绕结束:执行目标方法之后,模拟关闭事务");
        return obj;
    }

    //异常通知
    public void afterThrow(JoinPoint joinPoint,Throwable e){
        System.out.println("异常通知:"+e.getMessage());
    }

    //最终通知
    public void after(){
        System.out.println("最终通知:模拟方法结束后的释放资源");
    }
}

配置文件中加入:

<!-- 日志信息 -->
    <bean id="aspect" class="org.jit.sose.interceptor.Aspect" />
    <!-- aop编程 -->
    <aop:config>
        <aop:aspect ref="aspect">
            <aop:pointcut expression="execution(* org.jit.sose.controller.*.*(..))"
                id="pointCut" />
            <!-- 前置通知 -->
            <aop:before method="before" pointcut-ref="pointCut" />
            <!-- 后置通知 -->
            <aop:after-returning method="afterReturn"
                pointcut-ref="pointCut" returning="returnVal" />
            <!-- 环绕通知 -->
            <aop:around method="around" pointcut-ref="pointCut" />
            <!-- 异常通知 -->
            <aop:after-throwing method="afterThrow"
                pointcut-ref="pointCut" throwing="e" />
            <!-- 最终通知 -->
            <aop:after method="after" pointcut-ref="pointCut" />
        </aop:aspect>
    </aop:config>

我定义的切入点是控制层的所有类下的所有方法,网上有写的需要创建bean指向目标类的在SSM框架搭建完成的情况下是不需要的,现在运行项目就可以在控制台看到对应的执行信息,后期我再试试用户登录之后能不能将用户信息获取到打印出来。

猜你喜欢

转载自blog.csdn.net/single_cong/article/details/81115246