我真的是春天哲学的新人。在我们的项目中,我们有很多随机字符串,为了使它更容易我想创建自定义注释以将随机字符串注入字段。示例类
@Component
public class Tester{
@InjectRandomString(length = 25)
private String randomString;
public void testRandom() {
System.out.println(randomString);
}
}
这是我的BeanPostProcessor类
public class InjectRandomStringAnnotationBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
InjectRandomString annotation = field.getAnnotation(InjectRandomString.class);
System.out.println(field.getName());
if(annotation != null){
System.out.println("NOT NULL");
int length = annotation.length();
if(length < 0){
throw new IllegalArgumentException("Length is negative");
}
String random = UsefulStaff.getRandomString(length);
field.setAccessible(true);
ReflectionUtils.setField(field, bean, random);
}
}
return bean;
}
}
要注册这个课程,我已经使用以下Bean
创建了@Config类@Bean
public InjectRandomStringAnnotationBeanPostProcessor randomStringPostProcessor(){
return new InjectRandomStringAnnotationBeanPostProcessor();
}
为了测试它,我在RestController中创建了Tester对象
@Autowired
Tester tester;
@RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<String> test(@RequestParam(name = "message") String meString) throws TimeoutException, SocketTimeoutException, SocketException {
tester.sendMessageToQueue();
return ResponseEntity.ok(Enums.Error.SUCCESS.toString());
}
但每次调用此方法时,我的randomString都等于null。我做错了什么?
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectRandomString {
int length();
}