Spring bean fields injection

2019-04-05 16:43发布

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

3条回答
贪生不怕死
2楼-- · 2019-04-05 17:10

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:

查看更多
爷、活的狠高调
3楼-- · 2019-04-05 17:26

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)
查看更多
Lonely孤独者°
4楼-- · 2019-04-05 17:31

What you are asking for is not possible. Spring subscribes to convention over configuration. So it expects there to be setters and getters. While direct field injection is possible with Spring; and Spring uses Reflection to achieve this, Spring does not provide for reversing this process to use Reflection to access fields without setters or getters. Even Spring AOP implementation expects to find methods to structure it's proxies.

查看更多
登录 后发表回答