Wednesday, March 15, 2023

What is @PropertySource Annotation in Java and Spring? PropertySource Example Spring Boot

Hello Java developers, if you are using Spring Framework or Spring Boot in your new project and wondering what is property source in Spring Framework and how to use @PropertySource annotation then you have come to the right place. Earlier, I have shared the best books and online courses to learn Spring Framework and in this article, I will teach you how to use @PropertySource annotation in Spring to read Environment variables and inject properties using @Value annotation. In the Spring application, one of the files that are needed to provide properties to the Spring environment is the @Configuration classes. 

Spring @PropertySource annotation is used for this and this tutorial will explain how to use this to inject properties with @Value. The @PropertySource annotation adds a PropertySource to Spring's Environment in a simple and declarative manner. @Configuration classes must be used in combination with this class.


1. What is Spring @PropertySource Annotation?

The @PropertySource is a useful annotation for adding PropertySource to Spring's Environment and injecting properties into class attributes via @Value. This @PropertySource annotation adds a PropertySource to Spring's Environment in a simple and declarative manner. @Configuration classes must be used in combination with this class.

We will discuss the usage of the @PropertySource file with an example below.
 




Spring @PropertySource annotation with a simple example

In this example, we are reading database configuration from file config.properties file and set these property values to DataConfig class using the Environment.


The pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.5.0</version>
      <relativePath />
      <!-- lookup parent from repository -->
   </parent>
   <groupId>com.codexlabs</groupId>
   <artifactId>spring-cloud-config-server</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>spring-database-server</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>11</java.version>
      <spring-cloud.version>2020.0.3</spring-cloud.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

1. Create an application.properties file.
Let's create a config.properties file in the spring application and store the database properties in there.

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student_db
jdbc.username=admin
jdbc.password=admin123@
app.name=My application
app.version=1.1


Let's create a config.properties file in the spring application and store the database properties in there.



1.2 Create the DataConfig.java file
The @PropertySource injects the properties of database username, password, and app name from the application.properties into the spring.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(value = "application.properties", ignoreResourceNotFound = true)
public class DataConfig implements InitializingBean {


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

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;
    @Value("${app.name}")
    private String appName;
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        System.out.println(appName);
    }


}




1.3 Main class Application.java
We use this Application.java as a default class which has an entry point of the static main method.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

The output of the above program will be shown below.
jdbc:mysql://localhost:3306/student_db
admin
admin123@
My application


What is property source? How would you use @PropertySource in Spring? Example



In the above application, We get the properties from the application.properties file using the getProperty() method. 

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

@Value("${jdbc.username}")
private String username;

@Value("${jdbc.password}")
private String password;

@Value("${app.name}")
private String appName;


The main feature about properties and @PropertySource is that you can override it in various ways - for example with environment variables or application switches. application and see you in the next tutorial.  


That's all about @PropertySource annotation in Spring Framework. So in this tutorial, we discussed how to use @PropertySource annotation to work with properties in Spring. We have also seen a couple of examples of @value Annotation to read the properties from application.properties file. 

Other Java and Spring Tutorial you may like
  • How Spring MVC works internally? (answer)
  • How to upload a file in the Spring MVC application? (example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Spring Data JPA @Query Example (query example)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • Difference between @Component@Service, and @Controller in Spring (answer)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Spring Data JPA Repository (JpaReposistory example)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)

Thanks for reading this article so far. If you find this Spring @PropertySource Annotation Example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a Java beginner and want to learn the Core Spring Framework from scratch, and looking for some best online resources then you can also check out these free Spring Core and MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring MVC from scratch.     

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.