javaspringdependency-injectionjavabeans

How to access another field in springs @Value


like the title suggests I want to access another fields value using springs @Value annotation.

I want to do this to resolve the fields value by another fields id. Eg.: I have a field id and a field idContent. The idContent field should be automatically created by a method call to another bean using the id fields value.

I tried something like this:

public class MyBean {

    // This is set beforehand
    private final String id;

    @Value("#{otherBean.resolve(#id)}")
    private SomeObject idObject;

}

I get the following message back: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed


Solution

  • This could be done in plain java using constructor injection instead of field injection

    @Component
    public class MyBean {
       private final String id;
       private final SomeObject idObject;
    
       public MyBean(@Value("${id}") String id, OtherBean otherBean) {
          this.id = id;
          this.idObject = otherBean.resolve(id);
       }
    
       ...
    }
    

    Another option is to implement InitializingBean

    @Component
    public class MyBean implements InitializingBean {
       @Value("${id}")
       private String id;
    
       @Autowired
       private OtherBean otherBean;
    
       private SomeObject idObject;
    
       @Override
       public void afterPropertiesSet() {
          this.idObject = otherBean.resolve(id);
       }
    }
    

    I personally dislike field injection and always use constructor injection and final fields.