春天:@Value vs. @ Autowired [英] Spring: @Value vs. @Autowired

查看:160
本文介绍了春天:@Value vs. @ Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的应用程序中存在一些注入问题(使用Spring版本3.1.2).首先,我看到很多这样的代码:

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:

@Value("#{searchRequestBean}")
private SearchRequest searchRequest;

@Value("#{searchResponseBean}")
private SearchResponse searchResponse;

@Autowired
private SavedSearchService service;

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

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.

我希望对此有所了解,可以帮助我解决Session Bean遇到的一些问题.

I'm hoping that a better understanding of this will help me solve some issues I'm having with my Session bean.

推荐答案

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

@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.

@Autowired不能用于第一个示例:它不识别属性文件. @Autowired仅对于豆的DI .它比@Value更具体,但是您可以使用@Value做同样的事情.

@Autowired can't be used for the first example: It's not property file aware. @Autowired is only for DI of a bean. It is more specific than @Value, but you can use @Value to do the same thing.

这是@Value的很好的教程: http://www .mkyong.com/spring3/spring-value-default-value/

这篇关于春天:@Value vs. @ Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆