Enterprise Java

Accessing Values from application.properties in Spring Boot

Spring Boot makes it easier to build Java applications by giving us a simple way to set things up without lots of manual configuration. When setting up a Spring Boot application, a crucial part is handling properties, and the application.properties file is vital for this. In this guide, we’ll explore ways to accessing values from an application properties file in a Spring Boot application.

1. Create the application.properties file

By default, Spring looks for the application.properties file from the root classpath. To start, make a file called application.properties in the src/main/resources folder. This file is where we will keep all the setup details for our Spring Boot application. Later in this article, we’ll demonstrate various methods to get the values we’ve set in the mentioned application.properties file.

Note: If you like YAML better, you can use the application.yml file instead.

1.1 Example of application.properties file

We can configure a wide range of values in the application.properties file. These values can be related to various aspects of our application, including database configuration, server settings, logging, security, and custom application properties. Below is an example of custom values that are being configured in the application.properties file:

mail.server=smtp.javacodegeeks.com
mail.port=587
mail.username=jcg@javacodegeeks.com  
mail.password=javacodegeeks

1.2 Use @Value annotation in Spring Beans

To access these properties in our Java code, we can use the @Value annotation provided by Spring. This annotation allows us to inject values from properties files into our beans.

@Component
public class MailComponent {
    
    // injects smtp.javacodegeeks.com
    @Value("${mail.server}")
    private String server;

    // injects 587
    @Value("${mail.port}")
    private Integer port;

    // injects jcg@javacodegeeks.com
    @Value("${mail.username}")
    private String username;
    
    // injects javacodegeeks
    @Value("${mail.password}")
    private String password;

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    @PostConstruct
    public void displayProperties() {
        System.out.println("Server: " + server);
        System.out.println("Port: " + port);
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
    }
    
}

In this example, the values of mail.server, mail.port, mail.username and mail.password from the application.properties file will be injected into the server, port, username and password fields, respectively.

2. Accessing Values in Other Components or Services

Now that you have a component MailComponent that has access to the properties, we can use it in other components or services. Here is an example:

@RestController
public class MailController {

    @Autowired
    private MailComponent mailComponent;

    @GetMapping("/mail")
    public MailComponent getMailComponent() {
        return mailComponent;
    }

}

In the code above, we define a Spring MVC REST controller named MailController that exposes a single endpoint "/mail" that, when accessed via a GET request, returns the MailComponent object serialized as JSON. To test the HTTP GET method, enter the following command in a Terminal:

curl -X GET -i http://localhost:8080/mail

The output from running the above command is:

Fig 1.0 output showing how to access values from application properties in spring boot
Fig 1.0 output showing how to access values from application properties in spring boot

3. Use @ConfigurationProperties

We can use the @ConfigurationProperties annotation tool in Spring Boot to connect values from our application’s configuration file application.properties directly to our Java code. The @ConfigurationProperties annotation makes using configuration settings in our Java objects easy.

3.1 Create a Configuration Class

First, let’s create a Java class named MailConfiguration.java that will serve as our configuration class. We’ll annotate it with @Configuration to show that it holds special configuration settings for our application.

@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailConfiguration {

    // injects smtp.javacodegeeks.com
    private String server;    

    // injects 587
    private Integer port;  
    
    // injects jcg@javacodegeeks.com
    private String username;  
    
   // injects javacodegeeks
    private String password;

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }     

}

In this example, we’ve used @Configuration to mark the class as a configuration class, and @ConfigurationProperties(prefix = "mail") specifies that properties with the "mail" prefix in the application.properties file should be bound to this class.

3.2 Use @Autowired to Inject Configuration

Now, we can use the @Autowired annotation to inject our MailConfiguration into other Spring components or services like this:

@Component
public class CustomConfiguration {
    
    @Autowired
    private MailConfiguration mailConfiguration;
    
    @PostConstruct
    public void displayConfiguration() {
        System.out.println("Mail Server: " + mailConfiguration.getServer());
        System.out.println("Port: " + mailConfiguration.getPort());
        System.out.println("User Name: " + mailConfiguration.getUsername());
        System.out.println("Password: " + mailConfiguration.getPassword());
    }
    
}

In this component, CustomConfiguration is using @Autowired to inject the MailConfiguration bean, allowing us to access its properties. Now, when we run the application, the values from application.properties with the email prefix will automatically be bound to the MailConfiguration object. The CustomConfiguration component can then access these values.

4. Conclusion

Accessing values from the application.properties file in a Spring Boot application is a straightforward process. By using the @Value annotation, we can inject the values declared in a application.properties file into our Spring beans. Also, The @ConfigurationProperties annotation in Spring Boot provides us with an elegant solution for binding externalized configuration properties to Java objects. By adopting this practice, we can efficiently manage application properties, leading to a more organized code in our Spring Boot projects.

5. Download the Source Code

This was an example of how to access values from application properties in Spring Boot.

Download
You can download the full source code of this example here: Accessing Values from application.properties in Spring Boot

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button