开发者

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 {
    @开发者_JAVA技巧Property
    private String value;
}


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)


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:

  • Annotation-based container configuration
  • @Autowired and @Inject
  • @Resource


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜