T. Phillips
T. Phillips

Reputation: 61

Prevent runtime failure for empty @Value

I am trying to load a keystore and check the expiration date. So say I have two values

@Value(“${connections.keystoreA}”)
private String keystoreA;

@Value(“${connections.keystoreB}”)
private String keystoreB;

Some environments have 1 of these values, some have both. My question is, is there any way to prevent this from failing at runtime if one of the values isn’t there, other than using a default value?

Edit: I’d also like to make it so that I can add additional configs in the future, keystoreC, keystoreD, etc

Upvotes: 0

Views: 213

Answers (2)

Dimitar Spasovski
Dimitar Spasovski

Reputation: 2132

Because you don't want to use default values and you don't want to have Exception at runtime, you should use the org.springframework.core.env.Environment bean.

Just @Autowire the Environment in your component, and use the getProperty method to get a property from the yml configuration.

For example, if you want to get the value for my.connections.keystoreA you will use:

String value = environment.getProperty("my.connections.keystoreA");

Now, if there is a value for this key in your yml file, that value will be stored in the value variable. If there is no value for that key, then the value of the value variable will be null.

Upvotes: 1

Thiago Procaci
Thiago Procaci

Reputation: 1523

You can do an if/else in your application.properties and set a default value. For instance, your application.properties could be like:

my.connections.keystoreA=${connections.keystoreA:defaultA}
my.connections.keystoreB=${connections.keystoreB:defaultB}

The idea is: if connections.keystoreA does not exist, the string defaultA will be injected.

After that, you can inject the values:

@Value("${my.connections.keystoreA}") 
private String keystoreA;    
@Value("${my.connections.keystoreB}") 
private String keystoreB;

Doing this way, spring will not fail at runtime.

Another option is to use this if/else directely in the fields to set a default value if necessary:

@Value("${connections.keystoreA:defaultA}") 
private String keystoreA;    
@Value("${connections.keystoreB:defaultB}") 
private String keystoreB;

Upvotes: 1

Related Questions