cdimascio / dotenv-java

🗝️ Dotenv is a no-dep, pure Java module that loads environment variables from a .env file
https://github.com/cdimascio/dotenv-java
Apache License 2.0
444 stars 43 forks source link

Why .env variables not working in applicatio.properties file #50

Closed VaishnavGhenge closed 5 months ago

VaishnavGhenge commented 1 year ago

I have added dependency in build.gradle implementation 'io.github.cdimascio:dotenv-java:2.3.2'

MyApplication.java


@SpringBootApplication public class MovieApiApplication { public static void main(String[] args) { Dotenv dotenv = Dotenv.load(); String myEnvVar = dotenv.get("MONGO_CLUSTER"); System.out.println(myEnvVar);

SpringApplication.run(MovieApiApplication.class, args);

} } above code works but,

application.properties


spring.data.mongodb.database=${env:MONGO_DATABASE} spring.data.mongodb.uri=mongodb+srv://${env:MONGO_USER}:${env:MONGO_PASSWORD}@${env:MONGO_CLUSTER}

above code is not working as compiler is not able to resolve above env variables

ghost commented 1 year ago

i have the same problem. Can someone help me to solve this issue

diegoalfarog commented 6 months ago

The Dotenv module is load runtime, try using spring config to set DB creds in your main file.

import org.springframework.boot.jdbc.DataSourceBuilder;
...
@Bean
    @Primary
    DataSource dataSource() {
        DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
        Dotenv dotenv = Dotenv.configure().load();
        dataSourceBuilder.driverClassName("org.postgresql.Driver");
        dataSourceBuilder.url(dotenv.get("MAIN_DATASOURCE_URL"));
        dataSourceBuilder.username(dotenv.get("MAIN_DATASOURCE_USERNAME"));
        dataSourceBuilder.password(dotenv.get("MAIN_DATASOURCE_PASSWORD"));
        return dataSourceBuilder.build();
    }

DataSourceBuilder