java Spring:@Value 与 @Autowired
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29551761/
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: @Value vs. @Autowired
提问by Jeff Levine
I'm having some issues with injection in the application I'm working on (using Spring Version 3.1.2). To start with, I'm seeing a lot of code like this:
我在我正在处理的应用程序中遇到了一些注入问题(使用 Spring 版本 3.1.2)。首先,我看到很多这样的代码:
@Value("#{searchRequestBean}")
private SearchRequest searchRequest;
@Value("#{searchResponseBean}")
private SearchResponse searchResponse;
@Autowired
private SavedSearchService service;
Each of these three appears to have the effect of autowiring the specified bean/service into the class. What I don't understand is, what's the difference between @Value
and @Autowired
in these cases? Every example I find online seems to use @Value
to inject values from a properties file. In this case, SearchResponse
and SearchRequest
are abstract classes.
这三个中的每一个似乎都具有将指定的 bean/服务自动装配到类中的效果。我不明白的是,在这些情况下@Value
和之间有什么区别@Autowired
?我在网上找到的每个示例似乎都用于@Value
从属性文件中注入值。在这种情况下,SearchResponse
和SearchRequest
是抽象类。
I'm hoping that a better understanding of this will help me solve some issues I'm having with my Session bean.
我希望更好地理解这一点将帮助我解决我在使用 Session bean 时遇到的一些问题。
回答by Daniel Kaplan
@Value
can be used for injecting default values. A good example is to inject the default of a String
to be the value of a property file. In your example, @Value
is used to set the default value of a class to be a Spring managed bean.
@Value
可用于注入默认值。一个很好的例子是将 a 的默认值注入String
为属性文件的值。在您的示例中,@Value
用于将类的默认值设置为 Spring 托管 bean。
@Autowired
can't be used for the first example: It's not property file aware. @Autowired
is onlyfor DI of a bean. It is more specific than @Value
, but you can use @Value
to do the same thing.
@Autowired
不能用于第一个示例:它不知道属性文件。 @Autowired
是唯一一个bean的DI。它比 更具体@Value
,但您可以用@Value
它来做同样的事情。
Here is a good tutorial for @Value
: http://www.mkyong.com/spring3/spring-value-default-value/
这是一个很好的教程@Value
:http: //www.mkyong.com/spring3/spring-value-default-value/