Spring - Injecting values from Property Files

Spring - Injecting values from Property Files

In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource that we have described below.

@Value: The @Value annotation is a field, method or constructor level annotation. It is used to assign default values to fields and method arguments. We can also access the Spring environment variables and system variables using the @Value annotation. It supports the Spring Expression Language (SpEL) module. The @Value annotation is available in the org.springframework.beans.factory.annotation package.

Following code shows how to use @Value annotation:

@Value("${foo.email}")
 private String email; 

In the above code, we have defined the @Value annotation above the email field (environment variables.)

@PropertySource – The @PropertySource annotation provides a convenient mechanism to add property files to the Spring environment. It is used with the @Configuration annotation. According to Java 8, @PropertySource is repeatable annotation. It means we can have more than one PropertySource in a configuration class.  The @PropertySource annotation is available in the org.springframework.context.annotation package.

Following code shows how to use the @PropertySource annotation:

@Configuration
 @PropertySource("classpath:sport.properties")
 public class AppConfig { 
    …. 
 } 

In the above code, we have defined the @PropertySource("classpath:sport.properties") along with the @Configuration annotation in the AppConfig class. The sport.porperties is the properties file in which we have defined the properties.

Example of injecting properties file data using @Value and @PropertySource annotations

Here, we are going to create an example using the @Value and @PropertySource annotations to inject values from a properties file.

In this example, Fortune and Coach are the interfaces that consists unimplemented methods. The GoodLuckFortune and Cricket_Coach are the classes that implement the Fortune and Coach interface, respectively, and a sport.properties is a property file that contains some properties of Cricket_Coach class. The AppConfig class is a configuration class that contains the bean information.

Following are the steps to create an example of injecting properties using the @Value and @PropertySource annotations:

Fortune.java

public interface Fortune {
public String getDailyFortune();
} 

GoodLuckFortune.java

import org.springframework.stereotype.Component;
@Component
public class GoodLuckFortune implements Fortune{
public String getDailyFortune() {
return " Using @Bean : Goodluck For today..!!" ;
}
} 

Coach.java

public interface Coach {
public String getDailyTraining();
public String getFortuneService();
} 

Cricket_Coach.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Cricket_Coach implements Coach {
private Fortune fortuneService;
@Value("${foo.email}")
private  String email;
@Value("${foo.team}")
private String team;
public String getEmail() { 
return email;
}
public String getTeam() {
return team;
}
public Cricket_Coach(Fortune fortuneService) { 
this.fortuneService = fortuneService;
}
public String getDailyTraining() {
return " Using @Bean : Daily 5 hours of running..!" ;
}
public String getFortuneService() {
return fortuneService.getDailyFortune() ;
}
} 

In the above code, the @Value annotation instructs the Spring to find properties named "foo.email" and "foo.team" (from sport.properties file) and assigns its value to variables named email and team respectively. To access these variables, we have created getter methods for both variables.

sport.properties file

foo.email=myfavouritecoach@ProertiesFiles.com
foo.team= Spring Coders 

In the above code, we have defined two properties named email and team.

AppConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:sport.properties")
public class AppConfig {
// defining bean for GoodLuckFortune class
@Bean
 public Fortune goodLuckFortune() {
return new GoodLuckFortune();
}
//defining bean for Cricket_Coach class
@Bean
public Coach cricket_Coach() {
 return new Cricket_Coach(goodLuckFortune());
}
} 

App.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App 
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext appcont = new AnnotationConfigApplicationContext(AppConfig.class);
Cricket_Coach newCoach = appcont.getBean("cricket_Coach", Cricket_Coach.class);
System.out.println(newCoach.getDailyTraining());
System.out.println(newCoach.getFortuneService());
System.out.println(" Email :  " + newCoach.getEmail());
System.out.println(" Team :  " + newCoach.getTeam());
appcont.close();
}
} 

In the above code, we have created an object of Cricket_Coach class instead of Coach because the properties we have defined can be accessed by the Cricket_Coach object only.

OUTPUT

Spring - Injecting values from Property Files

Related Topics

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring MVC Form – Radio Button

A variety of form tags are available in Spring MVC for developing web applications, <form:radiobutton> tag is one of them. The radio button tag is used to choose only one option among a...

10 minutes read.

Spring AOP - @AfterThrowing Advice

Spring AOP - @AfterThrowing Advice As we have discussed in our previous tutorial, Advice is one of the essential concepts of the Spring AOP. The after throwing advice is one of the types of...

3 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring - Bean Scope

Spring - Bean Scope Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides...

6 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring MVC – @RequestParam

We have already discussed an example of Spring MVC in our previous tutorials. Here, we are going to discuss the @RequestParam annotation. In the last case, we had created a bean class for...

8 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.