Spring bean fields injection

浪子不回头ぞ 提交于 2019-12-05 17:05:56

问题


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

回答1:


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)



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/3854428/spring-bean-fields-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!