SpringBoot之自定义注解

import org.springframework.stereotype.Controller;

@MyAnnotation

@Controller

public class TestController {

@Autowired

private String name;

@MyAnnotation

public void aa(){

}

}

运行后target层注解消失:注解仅存在于源码中,在class字节码文件中不包含

Ⅱ、MyAnnotation注解为@Retention(RetentionPolicy.RUNTIME)时

**——**注解会在class字节码文件中存在,在运行时可以通过反射获取到

运行test.java:

package com.lv.controller;

import java.lang.annotation.Annotation;

public class Test {

public static void main(String[] args) {

// 反射

for(Annotation a:TestController.class.getAnnotations()){

System.out.println(a);

}

}

}

Ⅲ、取注解里的属性值

注解:MyAnnotation.java

String message() default “aaa”;

拿值:

package com.lv.controller;

import com.lv.annotation.MyAnnotation;

import java.lang.annotation.Annotation;

public class Test {

public static void main(String\[\] args) {

// 反射

    for(Annotation a:TestController.class.getAnnotations()){
        if(a instanceof MyAnnotation){
            System.out.println(((MyAnnotation) a).message());
        }
    }
}

}

Ⅳ、判断在该类有无该注解

测试:

package com.lv.controller;

import com.lv.annotation.MyAnnotation;

import java.lang.annotation.Annotation;

public class Test {

public static void main(String[] args) {

// 直接将MyAnnotation这注解取出

MyAnnotation myAnnotation=TestController.class.getAnnotation(MyAnnotation.class);

if(myAnnotation !=null){

System.out.println(myAnnotation.message());

}

}

}

三、完成切面日志操作


当我们在写增删改的时候,会有很多冗余的代码,后期修改很麻烦,如:

@RequestMapping(“/add”)

public String add(){

System.out.println(“xxx在增加”);

System.out.println(“增加成功”);

return “yes”;

}

我们就可以定义aop面向切面,将前面那部分放入前置通知,后面一部分后置通知

新建切面:LogAop.java

package com.lv.aop;

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.annotation.Pointcut;

import org.springframework.stereotype.Component;

@Aspect

//类不被识别,将类变成一个组件

@Component

@Slf4j

public class LogAop {

// 指定切入的规则,"…"代表可有参可无参

@Pointcut(“execution(* com.lv.controller.Controller.(…))”)

public void logger(){}

// 环绕通知

@Around(“logger()”)

public Object around(ProceedingJoinPoint point){

// 获得方法名称

Signature methodName=point.getSignature();

// 日志输出

log.info(methodName+“进来了”);

Long l1=System.currentTimeMillis();

// 让方法执行

Object obj=null;

try {

obj=point.proceed(point.getArgs());

} catch (Throwable throwable) {

throwable.printStackTrace();

}

log.info(methodName+“走了”+“\t耗时”+(System.currentTimeMillis()-l1));

return obj;

}

}

使用jrebel运行:

package com.lv.controller;

import com.lv.annotation.MyAnnotation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@MyAnnotation

//直接返回json数据

@RestController

//返回页面跳转数据

//@Controller

public class TestController {

@RequestMapping(“/add”)

public String add(){

return “yes”;

}

@RequestMapping(“/del”)

public String del(){

return “yes”;

}

@RequestMapping(“/upd”)

public String upd(){

return “yes”;

}

@RequestMapping(“/list”)

public String list(){

return “yes”;

}

}

使用注解来开发aop日志:

新建注解类:MyLog.java

package com.lv.annotation;

import java.lang.annotation.*;

@Inherited

@Documented

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface MyLog {

}

同样在切面类中,记得改变切入的规则

@Pointcut(“@annotation(com.lv.annotation.MyLog)”)

需要输出日志的方法就将新建的注解加上

四、完成前端响应反应


传入四个文件:

ResponseParse.java:

package com.lv.response;

import org.springframework.core.MethodParameter;

import org.springframework.http.MediaType;

import org.springframework.http.server.ServerHttpRequest;

import org.springframework.http.server.ServerHttpResponse;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**

  • @author hgh

*/

//响应增强类

@RestControllerAdvice

public class ResponseParse implements ResponseBodyAdvice {

@Override

public boolean supports(MethodParameter methodParameter, Class aClass) {

//返回值决定他是否需要进入beforeBodyWrite

return methodParameter.getMethod().isAnnotationPresent(ResponseResult.class);

}

@Override

public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

//更改返回值

if (o == null) {

return Result.success();

}

if (o instanceof Integer) {

return Result.failure(ResultCode.queryCode((Integer) o));

}

if (o instanceof ResultCode) {

return Result.failure((ResultCode) o);

}

if (o instanceof Result) {

return o;

}

return null;

}

}

ResponseResult.java:

package com.lv.response;

import java.lang.annotation.*;

/**

  • @author hgh

*/

@Retention(value = RetentionPolicy.RUNTIME)

@Documented

@Target({ElementType.METHOD})

public @interface ResponseResult {

}

Result.java:

package com.lv.response;

import lombok.Data;

import java.io.Serializable;

/**

  • 响应对象封装类

  • @author hgh

*/

@Data

public class Result implements Serializable {

private final int code;

private final String message;

private final T data;

/**

  • 私有构造, 只允许通过static调用构造

  • @param resultCode 结果枚举

  • @param data 响应数据

*/

private Result(ResultCode resultCode, T data) {

this.code = resultCode.getCode();

this.message = resultCode.getMessage();

this.data = data;

}

/**

  • 成功调用返回的结果(无数据携带)

  • @return Result

*/

public static Result success() {

return success(null);

}

/**

  • 成功调用返回的结果(数据携带)

  • @return Result

*/

public static Result success(T data) {

return new Result(ResultCode.SUCCESS, data);

}

/**

  • 失败调用返回的结果(数据携带)

  • @param resultCode 状态枚举

  • @param data 携带的数据

  • @return Result

*/

public static Result failure(ResultCode resultCode, T data) {

return new Result(resultCode, data);

}

/**

  • 失败调用返回的结果(无数据携带)

  • @param resultCode 状态枚举

  • @return Result

*/

public static Result failure(ResultCode resultCode) {

return failure(resultCode, null);

}

}

ResultCode.java:

package com.lv.response;

import java.io.Serializable;

/**

  • 响应结果码枚举

  • @author hgh

*/

public enum ResultCode implements Serializable {

/* 正常状态 */

SUCCESS(100, “成功”),

FAILURE(101, “失败”),

UNKNOWN(102, “未知响应”),

/**

  • 用户code范围: 200~300;

*/

USER_ACCOUNT_NOT_FIND(201, “用户名不存在”),

USER_ACCOUNT_DISABLED(202, “该用户已被禁用”),

USER_PASSWORD_NOT_MATCH(203, “该用户密码不一致”),

USER_PERMISSION_ERROR(204, “该用户不具备访问权限”),

USER_STATE_OFF_LINE(205, “该用户未登录”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值