自定义一个注解并实现注解返回后处理逻辑功能
自定义一个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CommunityOperation {
/**
* 主键
*/
String id() default "id";
/**
* 类型
*/
ContentTypeEnum type();
/**
* 类型为空则使用typeName获取
*/
String typeName() default "type";
}
JDK的元注解主要有@Target,@Retention,@Document,@Inherited用来修饰注解
@Target:表示java可以应用的元素类型
ElementType.TYPE:应用于类、接口(包括注解类型)、枚举
ElementType.FIELD:应用于属性(包括枚举中的常量)
ElementType.METHOD:应用于方法
ElementType.PARAMETER:应用于方法的形参
ElementType.CONSTRUCTOR:应用于构造函数
ElementType.LOCAL_VARIABLE:应用于局部变量
ElementType.ANNOTATION_TYPE:应用于注解类型
ElementType.PACKAGE:应用于包
ElementType.TYPE_PARAMETER:1.8版本新增,应用于类型变量)
ElementType.TYPE_USE:1.8版本新增,应用于任何使用类型的语句中(例如声明语句、泛型和强制转换语句中的类型)
@Retention:表明该注解的生命周期
RetentionPolicy.SOURCE:编译时被丢弃,不包含在类文件中
RetentionPolicy.CLASS:JVM加载时被丢弃,包含在类文件中,默认值
RetentionPolicy.RUNTIME:JVM 加载,包含在类文件中,在运行时可以被获取到
@Document:表明该注解标记的元素可以被Javadoc 或类似的工具文档化
@Inherited:表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解
增加切面处理注解
@AfterReturning
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Aspect
@Scope
@Component
@Slf4j
public class CommunityOperationAspect {
private ContentSendMsgFactory contentSendMsgFactory;
@Pointcut(value = "@annotation(com.xxxx.xxx.xxxxxx.annoation.CommunityOperation)")
public void activitySendMessage() {}
@AfterReturning(value = "activitySendMessage()&&@annotation(communityOperation)",returning = "result")
public Object beforeRequestIdVerify(JoinPoint joinPoint, Object result, CommunityOperation communityOperation) {
try {
JSONObject jsonObject=JSONObject.parseObject(JSONObject.toJSONString(result));
if(jsonObject.getIntValue("code")!= DefaultHttpResultStatus.SUCCESS.getCode()){
return result;
}
String id=StringUtils.EMPTY;
Integer code=communityOperation.type().getCode();
if(joinPoint.getArgs()[0] instanceof String){
id=String.valueOf(joinPoint.getArgs()[0]);
}else{
JSONObject params=JSONObject.parseObject(JSONObject.toJSONString(joinPoint.getArgs()[0]));
id=params.getString(communityOperation.id());
if(communityOperation.type().getCode()==null){
code=params.getInteger(communityOperation.typeName());
}
}
if(StringUtils.isEmpty(id)){
log.info("活动或评论发送消息到es未传ID");
}
contentSendMsgFactory.send(Long.valueOf(id),code);
} catch (Throwable throwable) {
log.error("统计社区用户失败{}",throwable);
}
return result;
}
@Autowired
public void setContentSendMsgFactory(ContentSendMsgFactory contentSendMsgFactory) {
this.contentSendMsgFactory = contentSendMsgFactory;
}
}
Around
@Around("activitySendMessage()&&@annotation(communityOperation)")
public Object beforeRequestIdVerify(ProceedingJoinPoint joinPoint, CommunityOperation communityOperation) {
Object result = null;
try {
result = joinPoint.proceed();
JSONObject jsonObject=JSONObject.parseObject(JSONObject.toJSONString(result));
if(jsonObject.getIntValue("code")== DefaultHttpResultStatus.SUCCESS.getCode()){
JSONObject params=JSONObject.parseObject(JSONObject.toJSONString(joinPoint.getArgs()[0]));
Integer code=communityOperation.type().getCode();
if(communityOperation.type().getCode()==null){
code=params.getInteger(communityOperation.typeName());
}
if(StringUtils.isEmpty(params.getString(communityOperation.id()))){
log.info("活动或评论发送消息到es未传ID");
}
contentSendMsgFactory.send(params.getLong(communityOperation.id()),code);
}
} catch (Throwable throwable) {
log.error("统计社区用户失败{}",throwable);
}
return result;
}
@Before
用于打印请求类名、方法名、请求参数
@Before(value = "pointcutController()")
public void before(JoinPoint joinPoint) {
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
List<Object> logArgs = streamOf(args)
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse))&& (arg instanceof MultipartHttpServletRequest))
.collect(Collectors.toList());
String argsJson = JSON.toJSONString(logArgs);
String beforeLog = String.format("开始调用%s.%s,参数为:%s", className, methodName, argsJson);
log.info(beforeLog);
}
使用
@CommunityOperation(id="id",type= ContentTypeEnum.ACTIVITY)
@PostMapping("/v1/publish")
public HttpResult<Boolean> publish(@NotNull @RequestBody final ActivityRequestBean activityRequestBean) {
return DefaultHttpResultFactory.fail("发布/取消失败。", Boolean.FALSE);
}