简体   繁体   English

春豆田注射

[英]Spring bean fields injection

Using Spring IoC allows to set bean properties exposed via setters: 使用Spring IoC允许设置通过setter公开的bean属性:

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

And the bean definition is: 而bean的定义是:

<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? 是否有任何现有的Spring Framework插件/类允许直接将bean字段作为属性公开而不定义setter? Something like this with the same bean definition: 像这样的bean具有相同的bean定义:

public class Bean {
    @Property
    private String value;
}

You can: 您可以:

  • use the @Value annotation and inject a property (using expression language) 使用@Value注释并注入一个属性(使用表达式语言)
  • take a look at Project Lombok , which will let you skip all setters and getters (and more) 看一看Project Lombok ,它会让你跳过所有的setter和getters(以及更多)

Spring supports annotation-based field injection out of the box for the JSR-250 @Resource annotation. Spring支持JSR-250 @Resource注释开箱即用的基于注释的字段注入。 Spring's own @Autowired and JSR 330 's @Inject also work . Spring自己的@AutowiredJSR 330@Inject 也有效

You just need to add this line to your context.xml : 您只需要将此行添加到context.xml

<context:annotation-config/>

Reference: 参考:

What you are asking for is not possible. 你要求的是不可能的。 Spring subscribes to convention over configuration. Spring订阅约定优于配置。 So it expects there to be setters and getters. 所以它希望有固定器和吸气剂。 While direct field injection is possible with Spring; 虽然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. 而Spring使用Reflection来实现这一点,Spring没有提供反转这个过程来使用Reflection来访问没有setter或getter的字段。 Even Spring AOP implementation expects to find methods to structure it's proxies. 即使Spring AOP实现也希望找到构造它的代理的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM