Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can @Value inject bean?

 
Les Hartzman
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Les Hartzman
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic