Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables in application.yml doesn't work with default values that start with a space

I have following application.yml:

sftp:
  sessionFactory:
    host: ${HOST:127.0.0.1}
    username: ${USERNAME:test}
    password: ${PASSWORD: test}

The password starts with a space. When starting the Spring Boot application it is crashing with:

    Caused by: mapping values are not allowed here
 in 'reader', line 26, column 25:
        password: ${PASSWORD: test}

When trying with ${PASSWORD:' test'}, the value of the password is password=' test' instead of password= test.

Before introducing the environment variables the application.yml looked like this:

sftp:
  sessionFactory:
    host: 127.0.0.1
    username: test
    password: ' test'

and everything worked properly.

Any idea how such a default value that starts with space can be specified? Thanks.

like image 939
Amalia Neag Avatar asked Apr 04 '18 05:04

Amalia Neag


People also ask

Can Yaml use environment variables?

Environment variable substitution is supported in both the great_expectations. yml and config variables config_variables. yml config file.

In which file can set default values for any environment variables?

env” file. You can set default values for any environment variables referenced in the Compose file, or used to configure Compose, in an environment file named .

Does environment variable override application properties?

Now, when your Spring Boot application starts, it will be given those environment variables, which will override your application. properties .

How do I set environment properties in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.


Video Answer


1 Answers

Edit: I want to clarify that SpEL only works for @Value bound properties as documented here. @ConfigurationProperties does not support SpEL expressions.

SpEL lets you combine raw strings and operaters. In your case you just want a plain string so you can define your property like so:

password: ${PASSWORD:#{' test'}}

##Example code

application.yaml

testing:
  my:
    username: ${USERNAME:user}
    password: ${PASSWORD:#{' test'}}

Testing.java

@Component
public class Testing {

  @Value("${testing.my.username}")
  String username;

  @Value("${testing.my.password}")
  String password;

  @PostConstruct
  public void post() {
    System.out.println("User: (" + username + ")");
    System.out.println("Pass: (" + password + ")");
  }

log

User: (user)
Pass: ( test)
like image 154
Pär Nilsson Avatar answered Oct 13 '22 22:10

Pär Nilsson