The official documentation on configuration outsourcing Spring Boot> has all the details about it.
First of all, parametrizing everything related to external access to your program is generally good practice, making testing and portability easier for new environments.
In the case of the framework, you simply define 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 have prefixed app
because it is good practice to segregate what is specific to your application from other settings. If you look at the other default settings in Spring Boot, you will see that they all follow a sort of hierarchy using prefixes.
To use the value of app.filesdir
in your program, you can inject the value into some Spring Bean any way:
@Component
public class MyBean {
@Value("${app.filesdir}")
private String name;
// ...
}
Ok, so far we have seen how to use the variable with its default value statically defined.
However, you can override the variable by 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 overwrite the value set in application.properties
.
Just be careful here because if you change an environment variable on another terminal or an interface on your Operating System, it will not immediately reflect on your terminal or IDE that is already open, have to close and open again to have the new value of the variable.
Finally, Spring Boot lets you 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 variable name defined in the environment.