How to Inject Property Value in Spring Bean

9 Flares Twitter 0 Facebook 3 Google+ 6 LinkedIn 0 9 Flares ×

Often we need to specify property values to a bean during its instantiation by Spring container. There are different ways to achieve the same.

  • Using the Value tag
  • Using Annotations

Using the Value Tag

Consider the class Car. We want to set the color property during its instantiation by the Spring container.



You can also use the short hand notation reducing the configuration xml by 1 line.


It is not a good practice to hard code values like we did. It is better to move the default values to a properties file for better manageability.
Next let us see how to do that.

We use the PropertiesPlaceHolder provided by Spring to substitute the values from the properties file. We store all configuration in a properties file named Make sure this properties file is stored in a folder that is part of the build class path.


Using Annotations

From Spring 3 onwards, the properties of beans can be set using annotations. This can be accomplished using the @Value annotation.


The key defined as default.color in the properties file will be substituted by Spring during the creation of the bean. Annotation approach is very handy as there are no XML configurations involved. But keep in mind that both XML approach and annotation approach has its own merits. Choose the one that satisfies your applications programming and deployment requirements.