Spring: @Value vs. @Autowired

微笑、不失礼 提交于 2019-12-24 02:57:20

问题


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;

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.

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


回答1:


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

Here is a good tutorial for @Value: http://www.mkyong.com/spring3/spring-value-default-value/



来源:https://stackoverflow.com/questions/29551761/spring-value-vs-autowired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!