@interface 自定义annotation 通过AOP来实现人员操作日志

来源:互联网 发布:期货配资软件 编辑:程序博客网 时间:2024/05/16 15:49

 @interface 自定义annotation 通过AOP来实现人员操作日志

首先 自定义annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {


   //此处实例是用来做token验证的,要是日志处理的话  可以在多定义几个参数 
    boolean save() default false;  //定义了save参数
 
    boolean remove() default false;  //定义了remove参数


}



2、 在需要记录日志的方法上引入注解

@RequestMapping(value = { "/xxxxxxxx" }, produces = { "application/json;charset=UTF-8" })
@ResponseBody
@Token(remove=true)    
public String xxxxxxxxx(HttpServletRequest request,HttpServletResponse response, HttpSession session) throws IllegalAccessException, InvocationTargetException, IntrospectionException{


3、 在spring.xml配置文件中加上aop注解

 <context:component-scan base-package="com.xxxxx.web.common.aspect" />
aop注解
      <aop:aspectj-autoproxy proxy-target-class="true" /> 


4、在  com.xxxxx.web.common.aspect 包下 新建切面bean   TokenAspect


@Component
@Aspect
public class TokenAspect {

//配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点

@Pointcut("execution(* com.fyyg.web..*(..))")
public void aspect(){}


* 配置前置通知,使用在方法aspect()上注册的切入点
* 同时接受JoinPoint切入点对象,可以没有该参数
 
@Before("aspect()")
public void before(JoinPoint joinPoint) throws ClassNotFoundException {
if(log.isInfoEnabled()){
log.info("before " + joinPoint);
}
String targetName = joinPoint.getTarget().getClass().getName();  
       String methodName = joinPoint.getSignature().getName();  
       Object[] arguments = joinPoint.getArgs();  
       Class targetClass = Class.forName(targetName);  
       Method[] methods = targetClass.getMethods();  
       Token annotation=null;
        for (Method method : methods) {  
            if (method.getName().equals(methodName)) {  
               Class[] clazzs = method.getParameterTypes();  
                if (clazzs.length == arguments.length) {  

    //获取到自定义注解,且在这个可以获取到  当前类注解的参数值 。如上,则可获取到remove值为true
               annotation = method.getAnnotation(Token.class);
                 //在此处可以进行逻辑操作
                  
               }  
           }  
       }  
        //return description;  
}

}

0 0
原创粉丝点击