Home > database >  Spring boot picking @value from default properties file
Spring boot picking @value from default properties file

Time:07-29

I am using @value annotation in spring boot to read a property

@Value(value = "${propName:#{null}}")
private String prop;

And based on if it is null or driving some logic in my code. In my dev environment I want to keep it null so I don't add it in that property file (application-dev.properties). But instead of getting it as null, it is reading the value from default application.properties file.

CodePudding user response:

By default, property values of external configuration sources (such as application.properties files) are always injected directly into your beans by using the @Value annotation.

One solution to your problem is moving the propName property from application.properties to application-{profile}.properties.

CodePudding user response:

Yes, this is the correct behavior based on Spring's property resolution. If you want to override it in your dev profile, simply add the property to your application-dev.properties, leaving the value empty. This will result in an empty String, not null, which you can convert to null with something like this:

@Value("${#{some_property == \"\"}:#{null}}")
private String prop;

It is probably a good idea to explicitly define these properties and give them values that make sense. Otherwise, you'll likely revisit this code in a few months and wonder what the heck is causing xyz.

You can read up on Spring and the order with which it resolves properties here but generally, you'd want to define variables that apply to all environments in your application.[properties][yaml], and then override them in the environment-specific properties files. In this case, it kind of sounds like this is a flag that's on or off depending on if the dev environment is set; you might consider something like this.

@Value("${property_to_drive_behavior:false}"
private Boolean prop;

This will default to false, so you don't need to add it to any properties file. If you want it set, override it in the environment-specific properties file. Booleans can be set in properties files using either the explicit true or false keywords or the values or 0 for false, 1 for true.

  • Related