import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Aspect @Component @Scope("protoptype") public class Result { private Result r; @Pointcut("execution(* com.ceair.unified.ws.*..*.*(..))") private void log() { } @Before("log() && args(t))") // T建议是map或者json类型,只要原始类型里有get()方法且有一个入参可以适配所有类型。 public <T> void before(JoinPoint joinPoint,T t) { try{ //需要校验的属性 String arr [] = new String []{"org","channel","name","container","signNum"}; for(String s : arr){ //获得T类中的get()方法 Method m = t.getClass().getMethod("get", Object.class); //调用t类中的get()方法,传入参数s if(m.invoke(t, s) == null || m.invoke(t, s) == ""){ r = Result.error(s+":不能为空"); } } }catch(Exception e){ r = Result.error("unkonw exception"); } r = Result.ok(); } @Around("log()") public Object around(ProceedingJoinPoint pjp) throws Throwable{ Object obj = null; if(r.getCode().equals(200)){ obj = pjp.proceed();//调用业务... }else{ //直接返回调用方,不会进入业务 return r; } /** * 业务执行完.... * 返回调用方 * */ return obj; } private Integer code; private String message; public static Result error(String message){ Result r = new Result(); r.setCode(-100); r.setMessage(message); return r; } public static Result ok(){ Result r = new Result(); r.setCode(200); return r; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
装饰着模式:不改变原有业务代码逻辑 增加功能。
Are you ok ?
标签:String,org,校验,无感,Result,AOP,import,message,public From: https://www.cnblogs.com/entertain/p/18141769