Monday 15 May 2017

Using @Value annotation in Spring

Hi guys today in one of the projects that I working on, I had to inject a value into one of the bean properties.
So I decided to use @Value annotation. Sharing the experience I have had.

I am using Spring 4.3.7.RELEASE. Here are the dependencies in my pom.xml

  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.7.RELEASE</version>
      </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>


spring-context depends up spring-beans, spring-core, spring-aop, spring-expression and commons-logging. So you do not have to worry about adding those. They will be automatically be added to your Maven dependencies in eclipse.
Go to the Dependencies Hierarchy tab, you will be able to clearly see the hierarchy.
 
Here is the class defining Java configuration.

@Configuration
@PropertySource("classpath:config/config.properties")
public class AppConfig {

    @Bean
    public Person getPerson(){
       
        return new Person();
    } 

}



@Configuration annotation is necessary here to indicate that this class will defined java configuration.
@PropertySource provides a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration.

Have created config folder in resources folder of my Maven project and added a file called config.properties to it.

Config.properties
person.name=Rizwan

Here is the Person bean
public class Person {

    @Value("${person.name}")
    private String name;
    private int age;


//..getter and setters

}
 The ${propertyname} syntax tells the Spring container to search for the specified  propertyname in Spring's property sources. 

Here is the complete project structure.


Thats it, test it.

public class App
{
    public static void main( String[] args )
    {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Person person = context.getBean(Person.class);
        System.out.println("Hello " + person.getName());
        ((AnnotationConfigApplicationContext)context).close();
    }
}


Output:
Hello Rizwan

In my next post, will try to add few more tips and tricks about @Value annotation, like working with default values and reading from System environment variables.
 

No comments:

Post a Comment