Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean fields injection

Using Spring IoC allows to set bean properties exposed via setters:

public class Bean {
    private String value;
    public void setValue(String value) {
        this.value = value;
    }
}

And the bean definition is:

<bean class="Bean">
    <property name="value" value="Hello!">
</bean>

Is there any existing plugins/classes for Spring Framework that allows to directly expose bean fields as properties without defining setters? Something like this with the same bean definition:

public class Bean {
    @Property
    private String value;
}
like image 701
Vladimir Avatar asked Oct 04 '10 10:10

Vladimir


2 Answers

You can:

  • use the @Value annotation and inject a property (using expression language)
  • take a look at Project Lombok, which will let you skip all setters and getters (and more)
like image 148
Bozho Avatar answered Oct 11 '22 12:10

Bozho


Spring supports annotation-based field injection out of the box for the JSR-250 @Resource annotation. Spring's own @Autowired and JSR 330's @Inject also work.

You just need to add this line to your context.xml:

<context:annotation-config/>

Reference:

like image 40
Sean Patrick Floyd Avatar answered Oct 11 '22 13:10

Sean Patrick Floyd