java Spring bean 字段注入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3854428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:41:51  来源:igfitidea点击:

Spring bean fields injection

javaspringinversion-of-controldependency-propertiesjavabeans

提问by Vladimir

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? Something like this with the same bean definition:

是否有任何现有的 Spring Framework 插件/类允许将 bean 字段直接公开为属性而不定义 setter?具有相同 bean 定义的类似内容:

public class Bean {
    @Property
    private String value;
}

回答by Bozho

You can:

你可以:

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

回答by Sean Patrick Floyd

Spring supports annotation-based field injection out of the boxfor the JSR-250@Resourceannotation. Spring's own @Autowiredand JSR 330's @Injectalso work.

对于JSR-250注释,Spring 支持开箱即用的基于注释的字段注入。Spring 自己的和JSR 330也适用@Resource@Autowired@Inject

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

您只需要将此行添加到您的 context.xml 中

<context:annotation-config/>

Reference:

参考:

回答by Robert Greathouse

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.

你所要求的是不可能的。Spring 订阅约定优于配置。所以它期望有 setter 和 getter。虽然 Spring 可以直接注入字段;而 Spring 使用反射来实现这一点,Spring 没有提供反转这个过程来使用反射来访问没有 setter 或 getter 的字段。甚至 Spring AOP 实现也希望找到构造它的代理的方法。