spring boot 自定义注解与AOP配合

  作者:记性不好的阁主

1、创建自定义注解




2、定义自定义注解


package cn.ucmed.merger.customaAnotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HelloAnnotation {
String printHello() default "HelloWord!";
}


相关说明:


@Target注解,是专门用来限定某个自定义注解能够被应用在哪些Java元素上面的

ElementType.METHOD 用于声明的方法上

ElementType.TYPE 用于类 接口上


@Retention注解,翻译为持久力、保持力。即用来修饰自定义注解的生命力。

RetentionPolicy.RUNTIME 表示在运行时阶段


@Inherited注解,是指定某个自定义注解如果写在了父类的声明部分,那么子类的声明部分也能自动拥有该注解。@Inherited注解只对那些@Target被定义为ElementType.TYPE的自定义注解起作用


@Documented注解,是被用来指定自定义注解是否能随着被定义的java文件生成到JavaDoc文档当中。


3、创建自定义注解拦截AOP




4、编写控制器日志拦截器、自定义注解拦截AOP类


控制器日志拦截器


package cn.ucmed.merger.aop;


import cn.ucmed.merger.model.ResultBean;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
* 日志打印
*
* @author HJH
* @since 2017-08-09
**/
@Order(1)
@Aspect
@Component
@Slf4j
public class LogPrintClass {


@Around("execution(* cn.ucmed.merger.api..*(..))")
public Object interceptor(ProceedingJoinPoint joinPoint) {
Object res = null;
JSONObject pms = new JSONObject();
String apiName = null;
try {
log.info("=======?=============================================================================");
MethodSignature signature = (MethodSignature) joinPoint
.getSignature();
Method method = signature.getMethod();
String[] names = signature.getParameterNames();
Object[] values = joinPoint.getArgs();
apiName = method.getName();
log.info("接口方法名称: " + apiName);
if (values != null && names != null) {
Class<?>[] types = method.getParameterTypes();
int j = Math.min(names.length, types.length);
j = Math.min(j, values.length);
for (int i = 0; i < j; i++) {
String key = types[i].getSimpleName() + " " + names[i];
if (!(values[i] instanceof javax.servlet.http.HttpServletRequest)
&& !(values[i] instanceof javax.servlet.http.HttpServletResponse)
&& !(values[i] instanceof org.springframework.web.multipart.commons.CommonsMultipartFile)
&& !(values[i] instanceof org.springframework.web.multipart.MultipartFile)) {
pms.put(key, values[i]);
}
}
}
log.info("接口请求入参: " + pms.toString());
res = joinPoint.proceed();
//出参
if (res instanceof ResultBean<?>) {
ResultBean<?> temp = (ResultBean<?>) res;
log.info("接口返回状态码:" + temp.getRet_code());
log.info("接口返回出参 :" + temp.toString());
}else {
log.info("接口返回出参 :" + res.toString());
}
} catch (Throwable throwable) {
log.error("LogPrintClass 出错,信息如下:", throwable);
}
return res;
}


}


自定义注解拦截AOP类

package cn.ucmed.merger.aop;


import cn.ucmed.merger.customaAnotation.HelloAnnotation;
import cn.ucmed.merger.model.ResultBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;




/**
* 日志打印
*
* @author HJH
* @since 2017-08-09
**/
@Order(2)
@Aspect
@Component
public class CustomAnnotaionPrintClass {

Logger Log = LoggerFactory.getLogger(CustomAnnotaionPrintClass.class);

@Around("@annotation(helloAnnotation)")
public Object interceptor(ProceedingJoinPoint joinPoint, HelloAnnotation helloAnnotation)throws Throwable {
String hello = helloAnnotation.printHello();
Log.info(hello); //应用场景:可以在这里做权限验证
return ResultBean.success(hello);
}


}


先在拦截方法中定义刚才自定义注解参数 HelloAnnotation helloAnnotation

在Around注解中 使用@annotation() 将参数包含进来

使用参数helloAnnotation.printHello()获取自定义注解的字段值



5、使用自定义注解


在需要拦截的控制器的方法上加上自定义注解即可。


package cn.ucmed.merger.api;

import cn.ucmed.merger.customaAnotation.HelloAnnotation;
import cn.ucmed.merger.model.ResultBean;
import cn.ucmed.merger.model.patient.Patient;
import cn.ucmed.merger.service.PatientServiice;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Api(tags = "【统一就诊人接口】")
public class PatientController {

@Autowired
private PatientServiice patientServiice;

@ApiOperation(value = "根据用户id获取就诊人列表")
@RequestMapping(value = "/getPatientList", produces = {"application/json"}, method = RequestMethod.GET)
@HelloAnnotation
public ResultBean getPatientList(
@ApiParam(value = "医院Id", required = true) @RequestParam("hospitalId") String hospitalId,
@ApiParam(value = "用户Id", required = true) @RequestParam("userId") String userId,
@ApiParam(value = "医联体Id", required = true) @RequestParam("unionId") String unionId
) {
List<Patient> patients = patientServiice.getPatientList(hospitalId, userId, unionId);
return ResultBean.success(patients);
}


}



日志打印结果:





关于更多自定义注解的说明请参阅文章:https://blog.csdn.net/xsp_happyboy/article/details/80987484



相关推荐

评论 抢沙发

表情

分类选择