javaspring-bootapplication.properties

How to access values in application.properties defined in another file in Spring Boot


I want to outsource my Database Connection and credentials from application.properties and access them in my application.properties.

I created a file called env.properties.

DB_USER=test
DB_PASSWORD=test
DB_URL=jdbc:mysql://localhost:3306/testDB

Then imported the file into my application.properties and tried to access the values.

spring.application.name=CampusFlow
spring.config.import=optional:env.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=Environment#getProperty("DB_URL")
spring.datasource.username=Environment#getProperty("DB_USER")
spring.datasource.password=Environment#getProperty("DB_PASSWORD")

Like this, I was not able to access the value of my variables. How would I access the values?


Solution

  • You have to use ${} notation.

    Example that worked for me:

    application.yml

    spring:
     config:
      import:
       env.properties
    myvar: ${TEST}
    

    env.properties

    TEST=myvar