define environment variable in application.properties

Asked

Viewed 4,588 times

1

I have a project in Spring boot where in application.properties I wanted to define the location of files that I will process. I don’t know the best way to do it. I wish I had the directory parameterizable in a system environment variable. I just can’t get it working.

Example

filesdir = ${BASEDIRFiles}

Right now I have

filesdir = /home/teste/

And on the system there was an environment variable named Basedirfiles with a directory where the files are. I didn’t want to define the directory clearly in application.properties. Any idea how to do it ?

2 answers

2


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.

0

Use the following syntax:

spring.datasource.username = ${MYSQL_DB_USERNAME}
spring.datasource.password = ${MYSQL_DB_PORT}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.