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.
Spring only can read
.propertiesand 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
EnvironmentPostProcessorinterface and override thepostProcessEnvironment()method. In this method, you can add the customPropertySourceto theEnvironmentobject.The
propertiesis a JavaPropertiesobject that you can create using SpringResourceinjection.How to turn a
ResourceintoPropertiesis a fairly trivial exercise that I'll leave to you.