there. I’m new to Java Spring Boot and I’m trying to set environment variables in application.yml.
I’ve added dotenv maven dependency:
<!-- https://mvnrepository.com/artifact/io.github.cdimascio/java-dotenv --> <dependency> <groupId>io.github.cdimascio</groupId> <artifactId>java-dotenv</artifactId> <version>5.1.3</version> </dependency>
I’ve set variables in the .env file:
SPRING_DATABASE_URL = jdbc://db_url SPRING_DATABASE_USERNAME = username SPRING_DATABASE_PASSWORD = password
And in my application.yml:
spring: datasource: url: ${SPRING_DATABASE_URL} username: ${env.SPRING_DATABASE_USERNAME} password: ${env.SPRING_DATABASE_PASSWORD}
While running application I’m getting jdbc error:
java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, ${SPRING_DATABASE_URL}
I’ve tried some solutions like:
export SPRING_DATABASE_URL = jdbc://db_url
or in application.yml:
url: ${env.SPRING_DATABASE_URL}
or
url: ${env.SPRING.DATABASE.URL}
or
url: ${SPRING.DATABASE.URL}
Am I doing something wrong or missing? I appreciate your help, thank you.
Advertisement
Answer
I recently ran in a similar issue and wanted to set environment variables via .env
with application.yml
– here is what I found out:
First, as you mentioned you have to add the java-dotenv dependency to pom.xml
:
<dependency> <groupId>io.github.cdimascio</groupId> <artifactId>dotenv-java</artifactId> <version>2.2.0</version> </dependency>
Then create your .env
file in the root of your project (where pom.xml
is located) and write your environment variables like e.g. ENV_PORT=8081
.
Before you can use this environment variable, you have to “bind” the content of the .env
file with Spring Boot when you start the app to make it globally available. According to this thread, this can be achieved by simply altering your Main entry point of spring (where you init the framework) like so:
@SpringBootApplication public class MySpringApplication { public static void main(String[] args) { Map<String, Object> env = Dotenv.load() .entries() .stream() .collect( Collectors.toMap(DotenvEntry::getKey, DotenvEntry::getValue)); new SpringApplicationBuilder(MySpringApplication.class) .environment(new StandardEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { super.customizePropertySources(propertySources); propertySources.addLast(new MapPropertySource("dotenvProperties", env)); } }).run(args); } }
That’s it, now you can reference to your environment variables in application.yml
like so:
server: port: ${ENV_PORT}
Hope this helps! If you are interested, here is also a full working example where I am using this approach.