spring Aop 实例

SpringMvc.xml中添加扫描日志类和使用aop注解。

<!--扫描全局日志 -->
    <context:component-scan base-package="com.company.wx.log" /> 

    <aop:aspectj-autoproxy expose-proxy="true"/>

 配置类:

@Aspect
@Component
public class GlobalLogConfig {
        @Autowired
        GlobalLogService globalLogService;
        
        //访问controller方法时调用
        Logger log = Logger.getLogger(GlobalLogConfig.class);
        @Before("execution(* com.company.wx.web.*.*(..))")
        public void beforeCheckToken(JoinPoint joinPoint) throws IOException {
            joinPoint.getArgs();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            //日志内容拼接
            String info="";
            //请求方法
            String requestMethod=(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
            info+=requestMethod;
            //请求参数
            if(joinPoint.getArgs().length>0){
                info+=joinPoint.getArgs()[0];
            }
            
            //规避GlobalLogController类
             if(!requestMethod.matches(".*GlobalLogController.*")){
                 setAndSave("请求方法",info);
             }
             
        }
        // 抛出异常时调用
        @AfterThrowing(value="execution(* com.company.wx.web.*.*(..))", throwing="ex") // 异常通知
        public void afterThrowing(JoinPoint joinPoint,Throwable ex) {
            //请求方法
            String requestMethod=(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
             //String info=requestMethod+"方法出现异常:"+ex.getCause().getMessage(); 
            String info=requestMethod+"方法出现异常:"+ex;
             setAndSave("异常", info);
        }
        
        //返回值时调用
        @AfterReturning(value="execution(* com.company.wx.web.*.*(..)) && !execution(* com.company.wx.web.GlobalLogController.*.*(..))", returning="result")
             public void afterReturning(JoinPoint joinPoint, Object result) {
            String requestMethod=(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
                 String info=requestMethod+"方法返回数据:"+JSONObject.toJSONString(result);
                 //规避GlobalLogController类
                 if(!requestMethod.matches(".*GlobalLogController.*")){
                     setAndSave("返回值",info);
                 }
             }
    
        
        /**设置日志内容并插入数据库
         * @param type 日志类型
         * @param info 日志内容
         * */
        private void setAndSave(String type,String info){
            GlobalLog globalLog=new GlobalLog();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String name=(String)request.getSession().getAttribute("name");//用户名
            if(name==null){
                name="";
            }
            globalLog.setUserName(name);
            String ip="";
            if (request.getHeader("x-forwarded-for") == null) {
                   ip= request.getRemoteAddr();
                }else{
                    ip=request.getHeader("x-forwarded-for");
            }            
            globalLog.setIp(ip);
    
            SimpleDateFormat format=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            String now=format.format(new Date());
            globalLog.setTime(now);
            
            globalLog.setType(type);
            globalLog.setInfo(info);
            
            globalLogService.insert(globalLog);
            
        }
}
原文地址:https://www.cnblogs.com/SunAutumn/p/7465698.html