使用注解 实现 切面编程
使用注解 实现 切面编程
1.定义注解
@Target({ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MsgSecCheck {String value();int idx() default 0;}
2.定义切面
@Aspect
@Component
public class MsgSecCheckAspect {@AutowiredWeixinMiniService weixinMiniService;/*** 切入点*/@Pointcut("@annotation(com.sandun.app.config.msgsec.MsgSecCheck)")public void methodArgs() {}/*** 操作** @param joinPoint*/@Before("methodArgs()")public void before(JoinPoint joinPoint) {MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();MsgSecCheck msgSecCheck = method.getAnnotation(MsgSecCheck.class);try {Object arg = joinPoint.getArgs()[msgSecCheck.idx()];String s;if(arg instanceof String){s=(String) arg;}else {Map map = BeanUtil.beanToMap(arg);s = map.get(msgSecCheck.value()).toString();}LogFactory.get().info("检测内容是否合规:"+s);boolean b = weixinMiniService.getSecCheckService().checkMessage(s);if(!b) {throw new ApiException("内容不合规,请检查");}} catch (WxErrorException ignored) {throw new ApiException("内容不合规,请检查");}}}
3.在控制器中添加注解
@MsgSecCheck("comment")public ApiResp insetAssistanceLeave(@Valid @RequestBody InsetAssistanceLeaveDTO insetAssistanceLeaveDTO){sdModeAssistanceLeaveService.insetAssistanceLeave(insetAssistanceLeaveDTO);return ApiResp.respOK("");}
其他代码片段
(1).留言实体累InsetAssistanceLeaveDTO
public class InsetAssistanceLeaveDTO {@NotNull(message = "请选择目标编号")@ApiModelProperty(value = "目标编号")private Integer assistanceId;@NotEmpty(message = "留言内容必填")@ApiModelProperty(value = "留言内容")private String comment;@ApiModelProperty(value = "回复留言编号")private Integer fId;public Integer getAssistanceId() {return assistanceId;}public void setAssistanceId(Integer assistanceId) {this.assistanceId = assistanceId;}public String getComment() {return comment;}public void setComment(String comment) {this.comment = comment;}public Integer getfId() {return fId;}public void setfId(Integer fId) {this.fId = fId;}
}
其他代码说明
这是一段检验微信发布内容是否合规的代码
控制其中加入注解MsgSecCheck 自动完成检验
注解参数
value:内容字段,不填时取idx的值
idx:参数下标,默认取第一个参数字段
其他注解说明
@Valid:校验数据完整性
@RequestBody:json提交
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
