![](/img/trans.png)
[英]Spring bean methods don't use the field value injected by ReflectionTestUtils.setField
[英]Unable to set field value via ReflectionUtils.setField
我正在創建一個自定義注釋,該注釋從特定間隔(最小,最大)設置隨機整數值。
@GenerateRandomInt(min=2, max=7)
我已經實現了BeanPostProcessor
接口。 這是它的實現:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Field[] fields=bean.getClass().getFields();
for (Field field : fields) {
GenerateRandomInt annotation = field.getAnnotation(GenerateRandomInt.class);
System.out.println(field.getName());
if(annotation!=null){
int min = annotation.min();
int max = annotation.max();
Random random = new Random();
int i = random.nextInt(max-min);
field.setAccessible(true);
System.out.println("Field name: "+field.getName()+" value to inject:"+i);
ReflectionUtils.setField(field,bean,i);
}
}
return bean;
}
這是spring上下文xml配置:
<bean class="InjectRandomIntAnnotationBeanPostProcessor"/>
<bean class="Quotes" id="my_quote">
<property name="quote" value="Hello!"/>
</bean>
但是,當我測試程序時,所需字段的值將為0(檢查10次)。 打印行名稱和要注入的值的代碼行也不起作用。 可能是什么錯誤? 如何正確定義字段定制注釋?
PS
使用此注釋的類:
public class Quotes implements Quoter {
@GenerateRandomInt(min=2, max=7)
private int timesToSayHello;
private String quote;
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public void sayHello() {
System.out.println(timesToSayHello);
for (int i=0;i<timesToSayHello;i++) {
System.out.println("Hello");
}
}
}
描述注解@GenerateRandomInt的接口
@Retention(RetentionPolicy.RUNTIME)
public @interface GenerateRandomInt {
int min();
int max();
}
代替getFields
使用getDeclaredFields
。
前者只給您public
領域,后者給您所有領域。
另一個技巧:由於您已經在使用ReflectionUtils
我建議使用doWithFields
方法來簡化您的代碼。
ReflectionUtils.doWithFields(bean.getClass(),
new FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
GenerateRandomInt annotation = field.getAnnotation(GenerateRandomInt.class);
int min = annotation.min();
int max = annotation.max();
int i = random.nextInt(max-min);
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(bean, field, i);
}
},
new FieldFilter() {
public boolean matches(Field field) {
return field.getAnnotation(GenerateRandomInt.class) != null;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.