自定义Java注解无法修改String类型字段值问题求助
问题原因
你定义的@Modify只是一个标记注解,Lombok自动生成的@Setter方法不会识别这个注解,只会执行简单的赋值逻辑,所以不会自动给字段值添加后缀。
解决方案
下面提供几种可行的实现方式:
方式一:手动编写Setter方法(简单直接)
放弃Lombok自动生成的Setter,手动实现字段的Setter方法,在方法内读取@Modify注解并处理后缀逻辑:
@Getter public class User { @Modify private String userName; public void setUserName(String userName) { try { Field field = User.class.getDeclaredField("userName"); Modify modify = field.getAnnotation(Modify.class); if (modify != null && userName != null) { this.userName = userName + modify.value(); } else { this.userName = userName; } } catch (NoSuchFieldException e) { e.printStackTrace(); this.userName = userName; } } }
方式二:使用AOP全局拦截Setter方法(适合多字段场景)
如果有多个字段需要使用@Modify注解,用AOP可以避免重复编写Setter逻辑。以Spring AOP为例:
1. 编写切面类
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Field; import java.lang.reflect.Method; @Aspect @Component public class ModifyAnnotationAspect { @Around("execution(* set*(..)) && args(value)") public Object aroundSetter(ProceedingJoinPoint joinPoint, String value) throws Throwable { // 获取Setter对应的字段名 Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); String fieldName = method.getName().substring(3); fieldName = Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1); // 获取目标对象和字段 Object target = joinPoint.getTarget(); Field field = target.getClass().getDeclaredField(fieldName); Modify modify = field.getAnnotation(Modify.class); // 处理后缀逻辑 String modifiedValue = value; if (modify != null && value != null) { modifiedValue = value + modify.value(); } // 用修改后的值执行原Setter方法 return joinPoint.proceed(new Object[]{modifiedValue}); } }
2. 保持原User类不变
@Getter @Setter public class User { @Modify private String userName; }
这样只要调用setUserName方法,AOP会自动拦截并给字段值添加指定后缀。
注意事项
- 处理
null值:如果传入的字段值为null,可以根据需求决定是否添加后缀(上面的代码中如果值为null则直接赋值,不添加后缀) - 非Spring项目:如果不是Spring环境,可以使用AspectJ的编译时织入来实现AOP逻辑
内容的提问来源于stack exchange,提问作者Nitinram Velraaj
相关产品推荐
相关产品推荐

