Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Spring and the fly likes Can @Value inject bean? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Can @Value inject bean?" Watch "Can @Value inject bean?" New topic
Author

Can @Value inject bean?

Les Hartzman
Greenhorn

Joined: Sep 19, 2012
Posts: 23
Using the STS Eclipse plugin for a Spring Template project for a Hibernate utility (using Spring 3.1), there is some code generated that I believe is injecting a bean vs. a value:

@Configuration
public class HibernateConfiguration {

@Value("#{dataSource}")
private DataSource dataSource;

And the XML file contains:

<jdbc:embedded-database id="dataSource" type="H2"/>

I've seen @Value used to inject properties, but is this is injecting the bean itself? And if so, why not use @Autowired or @Inject?

Thanks in advance.

Les

Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Yes it can,

Basically @Value isn't really about setting a value. So to speak. Meaning I would never do this

@Value("hello")
private String sayHello;

I would do

private String sayHello="hello"

So then what exactly is @Value for. Well it is for Spring Expression Language. And in the Spring Expression language it can evaluate to anything, any type.

So yes, the evaluation of @Value("#dataSource") is the bean with the id called dataSource, and that it what it was evaluated to the ref of the bean or the DataSource itself and the instance variable is set to that value.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Les Hartzman
Greenhorn

Joined: Sep 19, 2012
Posts: 23
Thanks for the response. The places where I've seen @Value used for strings has typically been when there is a properties file involved:

@Value(${jdbc.url})
private String jdbcUrl;

Could @Inject or @Autowired have been used in place as well?

Les
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Les Hartzman wrote:Thanks for the response. The places where I've seen @Value used for strings has typically been when there is a properties file involved:

@Value(${jdbc.url})
private String jdbcUrl;

Could @Inject or @Autowired have been used in place as well?

Les


In this particular case, no. In the dataSource case way above, yeah. I probably would have chosed @Autowired or @Inject instead. You could partially argue that with @Value is like @Autowired with @Qualifier without it being 2 annotations, now it is just one.

Mark
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Can @Value inject bean?