Spring wont read .env

239 Views Asked by At

My app wont get data from .env file. I have set

spring.config.import=optional:file:.env[.properties] 

in my application.properties. If i change this, it will immediately say file does not exist. So it sees the file (probably) but wont acces any data in it (returning null).

I tried implement dependency:

implementation 'io.github.cdimascio:java-dotenv:5.2.2'

I tried get values with:

@Value("${JWT_SECRET_KEY}")
  private String jwtSecret;

and

System.getenv();

I tried remove .env from gitignore I tried different imports like:

spring.config.import=optional:file:.env[.properties]
spring.config.import=file:.env[.properties] 

in application.properties I tried add: JWT_SECRET_KEY=${JWT_SECRET_KEY} directly in application.properties. I tried @ComponentScan with path annotation I tried get values with import org.springframework.core.env.Environment; I tried use envFile plugin in Intellij

Im working in Intellij, using corretto-17, SpringBoot, Gradle. .env is in root dir of a project.

1

There are 1 best solutions below

0
Abhijit Sarkar On

Spring only can read .properties and YAML files, which it determines based on the file extension. To read random files that are in properties format, you can create a custom property source as shown below.

Create a class that implements the EnvironmentPostProcessor interface and override the postProcessEnvironment() method. In this method, you can add the custom PropertySource to the Environment object.

public class CustomPropertySourceEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        PropertySource<?> customPropertySource = new PropertiesPropertySource("env", properties);
        environment.getPropertySources().addFirst(customPropertySource);
    }
}

The properties is a Java Properties object that you can create using Spring Resource injection.

@Value("classpath:.env")
private Resource resource;

How to turn a Resource into Properties is a fairly trivial exercise that I'll leave to you.