Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define not mandatory property in spring?

Tags:

java

spring

I'm using spring 3 with PropertyPlaceholderConfigurator.

My properties code looks like as following:

@Configuration public class MyProps {      @Value("${prop1}")     public String prop1;      ... } 

If I do not have a prop1 in my .properties file the spring fails to initialize it's context.

The question is how can I define that this property is not mandatory? some annotation, configuration?

like image 644
Julias Avatar asked Aug 02 '12 07:08

Julias


People also ask

What does @configuration do in Spring?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

Is application properties mandatory in Spring Boot?

So in a spring boot application, application. properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it.

What is @value annotation in Spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.


1 Answers

You could use a default value:

@Value("${prop1:}") public String prop1; 

and spring will inject an empty string if the property isn't defined. The syntax is ${property:defaultValue}.

like image 191
tibtof Avatar answered Sep 20 '22 15:09

tibtof