赞
踩
有些时候我们不想让一些权限不足的人看到一些敏感字段,因此我们可以使用注解+AOP+反射来实现将返回的对象中的敏感字段设置为null值。
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ShowField {
String value();
}
@Aspect public class FiledAspect { @Pointcut("execution(public * com.zkane.controller.*.*(..))") public void field() {} @Before("field()") public void doBefore(JoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); for (Object obj : args) { filterField(obj); } } @AfterReturning(returning = "obj", pointcut = "field()") public void doAfterReturning(Object obj) throws Throwable { filterField(obj); } private void filterField(Object obj) throws IllegalAccessException { Field[] fields = obj.getClass().getDeclaredFields(); for (Field field: fields) { field.setAccessible(true); ShowField showField = field.getAnnotation(ShowField.class); if (showField != null && showField.value().equals("Admin")) { field.set(obj, null); } } } }
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public FiledAspect filedAspect() {
return new FiledAspect();
}
}
public class User { private String name; @ShowField("Admin") private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。