DEV Community

realNameHidden
realNameHidden

Posted on

How to access a value defined in the application properties file in Spring Boot

Directory structure

Image description

pom.xml

<?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>3.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringBootApplicationProperties</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootApplicationProperties</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.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>

Enter fullscreen mode Exit fullscreen mode

application.properties

sid=2
sname=jhon
sadd=pune
Enter fullscreen mode Exit fullscreen mode

TestRunner

package com.example.demo.runner;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TestRunner implements CommandLineRunner {

    @Value("${sid}")
    private Integer sid;

    @Value("${sname}")
    private String sname;

    @Value("${sadd}")
    private String sadd;



    @Override
    public String toString() {
        return "TestRunner [sid=" + sid + ", sname=" + sname + ", sadd=" + sadd + "]";
    }



    @Override
    public void run(String... args) throws Exception {
        System.out.println(this.toString());
    }

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)