在使用注解和AOP完成接口对象属性的赋值的时候,返回对象查看后发现返回的对象属性值没有成功赋值。请问是什么原因呢?相关代码如下:
注解类:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParameterObjectAttributeAssignment {
}
切面类:
@Aspect
@Component
public class ParameterObjectAttributeAssignmentAspect {
/**
* 定义切点
*/
@Pointcut("@annotation(com.ywhk.cloud.db.persistence.dao.db.note.annotations.ParameterObjectAttributeAssignment)")
public void antoAddValue() {
}
/**
* 接口对象属性自动赋值
* @param joinPoint 切点
*/
@Before(value = "antoAddValue()")
public void beforeRandomValueAnnotatedMethod(JoinPoint joinPoint) {
// 参数数组
Object[] args = joinPoint.getArgs();
Random random = new Random();
for (Object arg : args) {
Field[] fields = arg.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(ParameterObjectAttributeAssignment.class)) {
field.setAccessible(true);
try {
if (field.getType().equals(int.class)) {
field.setInt(arg, 55);
} else if (field.getType().equals(Date.class)) {
field.set(arg,new Date());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
user类:
public class User {
private String name;
private String sex;
private String major;
@ParameterObjectAttributeAssignment
private int age;
Controller代码:
@PostMapping("/testAutoAddValue")
public ResponseEntity<User> testAutoFill(@RequestBody User user) throws InterruptedException {
return ResponseEntity.ok(user);
}
结果: