Spring app doesn't read environmental variables from .env

I have .env file in my project root folder along with pom.xml. Contents:
APP_PASSWORD=my-app-password
DATABASE_PASSWORD=Tomasm21-xi
DATABASE_USERNAME=Tomasm21
MAIL_USERNAME=myEmailAddress@gmail.com

and in application properties I use these values:
# Database Configuration
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myDB
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
//....
spring.mail.username=${MAIL_USERNAME}
spring.mail.password=${APP_PASSWORD}

I even added Dotenv Dependency:
    <!-- https://mvnrepository.com/artifact/io.github.cdimascio/java-dotenv -->
    <dependency>
        <groupId>io.github.cdimascio</groupId>
        <artifactId>java-dotenv</artifactId>
        <version>5.2.2</version>
    </dependency>

and configured it:
import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DotenvConfig {
    @Bean
    public Dotenv dotenv() {
        return Dotenv.configure().ignoreIfMissing().load();
    }
}

This class should set the system properties using the values from the Dotenv bean:
@Configuration
public class AppConfig {
    private final Dotenv dotenv;

    @Autowired
    public AppConfig(Dotenv dotenv) {
        this.dotenv = dotenv;
        System.setProperty("DATABASE_USERNAME", dotenv.get("DATABASE_USERNAME"));
        System.setProperty("DATABASE_PASSWORD", dotenv.get("DATABASE_PASSWORD"));
        System.setProperty("MAIL_USERNAME", dotenv.get("MAIL_USERNAME"));
        System.setProperty("APP_PASSWORD", dotenv.get("APP_PASSWORD"));
    }
}

But actually it doesn't work and I get an exception when I launch my application.
I'm on Windows 10.
Was this page helpful?