Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: @Value vs. @Autowired

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.

like image 352
Jeff Levine Avatar asked Dec 09 '22 04:12

Jeff Levine


1 Answers

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

like image 132
Daniel Kaplan Avatar answered Dec 11 '22 08:12

Daniel Kaplan