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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:29:24  来源:igfitidea点击:

Spring: @Value vs. @Autowired

javaspringdependency-injectionautowiredspring-annotations

提问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 @Valueand @Autowiredin these cases? Every example I find online seems to use @Valueto inject values from a properties file. In this case, SearchResponseand SearchRequestare abstract classes.

这三个中的每一个似乎都具有将指定的 bean/服务自动装配到类中的效果。我不明白的是,在这些情况下@Value和之间有什么区别@Autowired?我在网上找到的每个示例似乎都用于@Value从属性文件中注入值。在这种情况下,SearchResponseSearchRequest是抽象类。

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

@Valuecan be used for injecting default values. A good example is to inject the default of a Stringto be the value of a property file. In your example, @Valueis used to set the default value of a class to be a Spring managed bean.

@Value可用于注入默认值。一个很好的例子是将 a 的默认值注入String为属性文件的值。在您的示例中,@Value用于将类的默认值设置为 Spring 托管 bean。

@Autowiredcan't be used for the first example: It's not property file aware. @Autowiredis onlyfor DI of a bean. It is more specific than @Value, but you can use @Valueto 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/

这是一个很好的教程@Valuehttp: //www.mkyong.com/spring3/spring-value-default-value/