自定义aop注解,并获取注解中的参数

自定义注解:

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; 
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface Ypjglog {   
	String description() default "";
}

自定义切面:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

@Aspect
public class LogAspect {	   	
	@Around(value = "within(@org.springframework.stereotype.Controller *) && @annotation(Ypjglog)")//对有@Controller注解类中的带有@Ypjglog的方法记录访问日志
	public Object saveLog(ProceedingJoinPoint pjp) {
		Signature signature = pjp.getSignature();//此处joinPoint的实现类是MethodInvocationProceedingJoinPoint
		MethodSignature methodSignature = (MethodSignature) signature;//获取参数名
		Ypjglog ypjglog = methodSignature.getMethod().getAnnotation(Ypjglog.class);
		System.out.println(ypjglog.description());
		try {
			return pjp.proceed(); //直接pjp.proceed(),没有return ,前台页面获取不到ajax数据
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}

control类:

@Controller
@RequestMapping({ "/cfdp" })
public class CfdpController {
	
	@Ypjglog(description = "首页")
	@RequestMapping("/cfdpList")
	public String cfdp(Model model,String url) {
		return "pages/cfdp/cfdpList";
	}
}

你可能感兴趣的:(java)