set environment variable in application.properties

1

I have a project in Spring boot where in application.properties I wanted to set the file location that I'm going to process. I do not know the best way to do it. I wanted to have the parameterizable directory in an environment variable in the system. I just can not get it to work.

Example

filesdir = ${BASEDIRFiles}

At this moment I have

filesdir = /home/teste/

And the system had an environment variable named BASEDIRFiles with a directory where the files are. I did not want to clearly define the directory in application.properties. Any ideas on how to do this?

    
asked by anonymous 04.01.2017 / 12:33

2 answers

2

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.

    
17.10.2017 / 18:55
0

Use the following syntax:

spring.datasource.username = ${MYSQL_DB_USERNAME}
spring.datasource.password = ${MYSQL_DB_PORT}
    
13.02.2017 / 14:38