r/SpringBoot • u/Tony_salinas04 • Jan 13 '26
Question What is the best way to handle environment variables in Spring Boot?
Until now I haven't had to deal with these, I've looked into it and I see there are many ways, which one do you recommend using and why?
22
Upvotes
11
u/deividas-strole Jan 13 '26
application.properties file for property placeholders + .env file where you will put your secrets. This is the most straightforward way. I use this all the time. Just put your environment variables inside the file. Example:
spring.datasource.url=${DB_URL} spring.datasource.username=${DB_USER} spring.datasource.password=${DB_PASSWORD}
--server.port=8081export SERVER_PORT=8081/configsubdirectoryI would recommend the first approach.
7
u/Dry_Try_6047 Jan 13 '26
Environment variables are available to you in Spring 's Environment abstraction. So the answer is to handle them in the same way you would handle any other property. In 2026, I would recommend binding to a ConfigurationProperties object or even pulling it directly from an EnvironmentAware bean over injecting with @Value annotations, but all 3 will work.
2
u/FragrantScallion848 Jan 16 '26
You could use a secret manager for handling environment variables especially in production environments. Such as bitwarden or infisical
2
u/smutje187 Jan 13 '26
Inject a @Value and use Springs environment mechanism
1
u/pokeapoke Jan 13 '26
@ConfigurationProperties mapped to POJOs. Spring handles nested objects so you can model your configuration as classes in a typesafe way. I also recommend using .properties file to .yaml, the reason is that it is WAY easier to search for foo.bar.baz rather than for foo: bar: baz with varying levels of indentation and whitespace. Once you start creating separate autoconfiguration artifacts etc. the IDE help only takes you so far.
1
u/pradeepngupta Jan 14 '26
One rule of thumb i follow in Spring Boot-
If your config: changes per environment includes secrets affects behavior
Go for Environment variables + @ConfigurationProperties
And i see most of users already commented most of the things
3
u/PM_Me_Your_Java_HW Jan 13 '26
Unless you have a corporate requirement, can anyone point out an issue with running the application in a docker container and then set environment variables in the dockerfile? With this route, all you'll need to do is call System.getEnv().
1
u/TurkmenTT Jan 13 '26
application.properties
1
u/Luolong Jan 17 '26
Just learn to read documentation. It’s all there.
Use what fits your situation and looks simplest. There are so many ways because there are so many different use cases.
1
u/citizen10002 Mar 02 '26
You don't mention what editor. I might be a weirdo I use vs code, just make a launch.json entry for java app. include:
Put the .env file in your workspace root dir. Basically it injects the variables like you did an export $VARIABLE_NAME on your own, every single time.