Springmvc 自定义@自定义注解(头标注、头标签)


安装网络上的许多教程配置自定义注解,配置的我心都累了,我把整个流程都发布出来希望能够帮助到一些需要的人


1.引入架包 重中之重

<!-- AOP -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.9</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>


2.配置XML(springmvc-servlet.xml 每个人的工程里面的名字可能不一样)

<!-- 激活自动代理功能 -->
	<aop:aspectj-autoproxy proxy-target-class="true"/>
	<!-- 用户服务对象 -->
	<bean id="userService" class="com.olcps.Annotation.LogAspect" />


代码结构如下



3.定义一个接口

package com.olcps.Annotation;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.lang.annotation.*;

/**
 * Created by LK on 2016/9/2.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
@Documented
//最高优先级
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface Log {
    String name() default "";
}

4.定义一个错误

package com.olcps.Annotation;

/**
 * Created by LK on 2016/9/2.
 */
public class catch_ extends Exception {
    private static final long serialVersionUID = 1364225358754654702L;
    public catch_() {
        super("HTTP请求超出设定的限制");
    }
    public catch_(String message) {
        super(message);
    }
}


5.定义一个执行注解的类

package com.olcps.Annotation;

import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by LK on 2016/9/2.
 */

@Aspect
@Component
public class LogAspect {

    ThreadLocal<Long> time=new ThreadLocal<Long>();
    ThreadLocal<String> tag=new ThreadLocal<String>();

    /*
    * 目标方法执行前
    * */
    @Before("@annotation(com.olcps.Annotation.Log)") //执行@接口
    public void beforeExec(JoinPoint joinPoint) throws catch_ {

        time.set(System.currentTimeMillis());
        tag.set(UUID.randomUUID().toString());

        //info(joinPoint);
        try {
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = null;
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest) {
                    request = (HttpServletRequest) args[i];
                    break;
                }
            }
            args[2] = "132222";
            if (args[2] != "132222") {
                throw new catch_("方法中缺失HttpServletRequest参数");
            }
            /*MethodSignature ms=(MethodSignature) joinPoint.getSignature();
            Method method=ms.getMethod();
            System.out.println(method.getAnnotation(Log.class).name()+"标记"+tag.get());*/
        } catch (catch_ e) {
            throw e;
            //System.out.println("Error:121313121212");
        }
    }
    /*
    * 目标方法执行后
    * */
    @After("@annotation(com.olcps.Annotation.Log)")
    public void afterExec(JoinPoint joinPoint){
        MethodSignature ms=(MethodSignature) joinPoint.getSignature();
        Method method=ms.getMethod();
        System.out.println("标记为"+tag.get()+"的方法"+method.getName()+"运行消耗"+(System.currentTimeMillis()-time.get())+"ms");
    }

    /**
     @AfterReturning – 目标方法返回后执行,如果发生异常不执行
     @AfterThrowing – 异常时执行
     **/

    /*
    * 在执行上面其他操作的同时也执行这个方法
    * */
    @Around("@annotation(com.olcps.Annotation.Log)")
    public void aroundExec(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("我是Around,来打酱油的");
        pjp.proceed();
    }

    private void info(JoinPoint joinPoint){
        System.out.println("--------------------------------------------------");
        System.out.println("King:\t"+joinPoint.getKind());
        System.out.println("Target:\t"+joinPoint.getTarget().toString());
        Object[] os=joinPoint.getArgs();
        System.out.println("Args:");
        for(int i=0;i<os.length;i++){
            System.out.println("\t==>参数["+i+"]:\t"+os[i].toString());
        }
        System.out.println("Signature:\t"+joinPoint.getSignature());
        System.out.println("SourceLocation:\t"+joinPoint.getSourceLocation());
        System.out.println("StaticPart:\t"+joinPoint.getStaticPart());
        System.out.println("--------------------------------------------------");
    }


}

6.使用

  @Log(name = "测试的AAAAAAAAAAAAAA")
    @RequestMapping(value = "/UserDemo", method= RequestMethod.GET)
    public @ResponseBody Object UserDemo(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="Csd", defaultValue="1") String Csd) throws ScriptException, NoSuchMethodException, IOException {}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值