给出一个课程:
public ClassA {
@Autowired
@SomeAnnotation("foo")
private ClassB bar;
}
@Component
@Scope(prototype)
public ClassB {
private String someString;
}
我想编写一些bean处理器(post construct ...),它可以在ClassB
构建时访问@SomeAnnotation
注入ClassB
的内容someString
我可以将{{1}}的值设置为“foo”。
我知道这不是IoC而且我猜它不能完成。
答案 0 :(得分:1)
您可以使用@PostConstruct
ClassA
来执行此类操作:
@PostConstruct
public void postConstruct(){
SomeAnnoation someAnnotation = this.getClass().getField("bar").getAnnotation(SomeAnnotation.class);
bar.someString(someAnnotation.value());
}
更新: - 使用BeanPostProcessor的常规解决方案:
public class SomeAnnotationFieldInitalizer implements BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Field[] fields = bean.getClass().getFields();
if (fields!=null){
for (Field field:fields){
SomeAnnotation someAnnotation = field.getAnnotation(SomeAnnotation.class);
if (someAnnotation!=null){
try {
ReflectionUtils.makeAccessible(field);
field.set(bean, someAnnotation.value());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return bean;
}
}