Spring中自定义注解与使用

版权声明:本文为博主原创文章,转载请标明出处和链接! https://blog.csdn.net/junmoxi/article/details/79979260

以日志打印为例:

一、注解接口

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Description: 日志注解
 * @author pibigstar
 */
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoggerManage {

	public String description();
}

二、解析注解

package com.favorites.comm.aop;


import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Service;

/**
 * @Description: 日志管理
 * @author pibigstar
 */
@Aspect
@Service
public class LoggerAdvice {
	
	private Logger logger = Logger.getLogger(this.getClass());

	@Before("within(com.favorites..*) && @annotation(loggerManage)")
	public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
		logger.info("执行 " + loggerManage.description() + " 开始");
		logger.info(joinPoint.getSignature().toString());
		logger.info(parseParames(joinPoint.getArgs()));
	}
	
	@AfterReturning("within(com.favorites..*) && @annotation(loggerManage)")
	public void addAfterReturningLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
		logger.info("执行 " + loggerManage.description() + " 结束");
	}
	
	@AfterThrowing(pointcut = "within(com.favorites..*) && @annotation(loggerManage)", throwing = "ex")
	public void addAfterThrowingLogger(JoinPoint joinPoint, LoggerManage loggerManage, Exception ex) {
		logger.error("执行 " + loggerManage.description() + " 异常", ex);
	}

	private String parseParames(Object[] parames) {
		if (null == parames || parames.length <= 0) {
			return "";
		}
		StringBuffer param = new StringBuffer("传入参数[{}] ");
		for (Object obj : parames) {
			param.append(ToStringBuilder.reflectionToString(obj)).append("  ");
		}
		return param.toString();
	}
	
}

@Aspect相当于拦截器,使其面向切面

三、使用

@RequestMapping(value = "/login", method = RequestMethod.POST)
@LoggerManage(description="登陆")
public ResponseData login(User user,HttpServletResponse response) {
}

阅读更多

扫码向博主提问

java派大星

从HelloWorld到改变世界!
  • 擅长领域:
  • java
  • python爬虫
去开通我的Chat快问
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页