1、在sdk中加入拦截器主类
package com.self.activity.sdk.aop;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import com.self.activity.sdk.bean.Result;
import com.self.activity.sdk.config.CodeProperties;
import com.self.activity.sdk.exception.BusinessException;
public class BaseValidateHandler {
public Object validate(ProceedingJoinPoint joinPoint) {
try {
Object[] args = joinPoint.getArgs();
// 输入参数对象通用校验
for (Object arg : args) {
if (!(arg instanceof BeanPropertyBindingResult))
continue;
BeanPropertyBindingResult result = (BeanPropertyBindingResult) arg;
if (!result.hasFieldErrors())
continue;
List
for (FieldError error : fieldErrors) {
String codePattern = error.getDefaultMessage();
String fieldName = error.getField();
String code = this.fetchMsgCode(codePattern);
String displayMsg = this.getDisplayMessage(codePattern, fieldName);
return new Result
}
// 具体业务处理
return joinPoint.proceed();
} catch (BusinessException ex) {
// 业务异常
return new Result
protected String getDisplayMessage(String codePattern, String fieldName) {
String code = fetchMsgCode(codePattern);
String[] params = fetchMsgParams(codePattern, fieldName);
return CodeProperties.getInstance().getValue(code, params);
}
private String fetchMsgCode(String codePattern) {
if (StringUtils.isEmpty(codePattern)) {
return null;
}
String[] fields = codePattern.split(",");
return fields[0];
}
private String[] fetchMsgParams(String codePattern, String fieldName) {
if (StringUtils.isEmpty(codePattern)) {
return new String[] {};
}
String[] configParams = codePattern.split(",");
String[] params = new String[configParams.length];
params[0] = fieldName;
if (configParams.length > 1) {
System.arraycopy(configParams, 1, params, 1, configParams.length - 1);
}
return params;
}
}
2、在拦截器中书写内容
package com.self.activity.handler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.self.activity.sdk.aop.BaseValidateHandler;
@Aspect
@Component
@Order(0)
public class ValidateHandler extends BaseValidateHandler {
@Pointcut("execution(* com.self.activity.controller.*Controller.*(..))")
public void validateMethod(){}
@Around("validateMethod()")
public Object validate(ProceedingJoinPoint joinPoint){
return super.validate(joinPoint);
}
}
aop是面向切面变成,是与oop面向对象编程相对的。
AOP、OOP在字面上虽然非常类似,但却是面向不同领域的两种设计思想。OOP(面向对象编程)针对业务处理过程的实体及其属性和行为进行抽象封装,以获得更加清晰高效的逻辑单元划分。 而AOP则是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果。这两种设计思想在目标上有着本质的差异。