The official documentation on configuration outsourcing Spring Boot has all the details on this.
First of all, parameterizing everything regarding external access to your program is good practice in general, facilitating testing and portability to new environments.
In the case of the framework, just set an entry in the file application.properties
(or application.yaml
, which I believe is more readable and has been recommended recently), as follows:
app.filesdir=/home/test
I put the prefix app
because it is good practice to segregate what is specific to your app from other settings. If you look at the other default settings of Spring Boot, you will see that they all follow a kind of hierarchy using prefixes.
To use the value of app.filesdir
in your program, you can inject value into some Spring Bean any so:
@Component
public class MyBean {
@Value("${app.filesdir}")
private String name;
// ...
}
Ok, so far we’ve seen how to use the variable with its statically defined default value.
However, you can overwrite the variable using, for example, a parameter in the command that starts the Spring Boot Application:
java -jar myapp.jar --app.filesdir=/home/teste
On the other hand, if you want to set the value in an environment variable, you can do this too and, in the order specified in the documentation, it will override the value set in application.properties
.
Just be careful here because if you change an environment variable in another terminal or in an interface of your Operating System, it will not immediately reflect on your terminal or IDE that is already open, you would have to close and open again to get the new variable value.
Finally, Spring Boot allows you to reference environment variables in your configuration file. Example:
app.filesdir=${APP_FILES_DIR}
However this is useful only when you want to use a different variable name internally in the application relative to the name of the variable defined in the environment.
Thanks for the explanation! I get the idea.
– user2989745