dotenv-java icon indicating copy to clipboard operation
dotenv-java copied to clipboard

Why .env variables not working in applicatio.properties file

Open VaishnavGhenge opened this issue 2 years ago • 2 comments

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

VaishnavGhenge avatar Apr 20 '23 19:04 VaishnavGhenge

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

ghost avatar May 22 '23 09:05 ghost

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

diegoalfarog avatar Apr 16 '24 21:04 diegoalfarog