我可以在要注入的bean实例上访问注释

时间:2012-10-19 10:59:13

标签: spring

给出一个课程:

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而且我猜它不能完成。

1 个答案:

答案 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;
    }
}