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
Spring bean fields injection
提问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
@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)
- 使用
@Value
注解并注入一个属性(使用表达式语言) - 看看Project Lombok,它会让你跳过所有的 setter 和 getter(以及更多)
回答by Sean Patrick Floyd
Spring supports annotation-based field injection out of the boxfor the JSR-250@Resource
annotation. Spring's own @Autowired
and JSR 330's @Inject
also work.
对于JSR-250注释,Spring 支持开箱即用的基于注释的字段注入。Spring 自己的和JSR 330的也适用。@Resource
@Autowired
@Inject
You just need to add this line to your 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 实现也希望找到构造它的代理的方法。