There are a lot of tutorials and examples on how to use spring properties, be it a .properties or .yaml file. Here, we will take a look at most common scenarios.
Lets see how we can:
- Inject a property value into a field, using @Value annotation
- Use a property value inside annotation
- Have a list of objects created from properties
Example of .properties configuration:
# Simple properties app.config.message=Hello app.config.customBeanName=CustomBeanName # Array of properties app.config.beans[0].name=customBean0ID app.config.beans[0].text=customBean0TxtProperty app.config.beans[1].name=customBean1ID app.config.beans[1].text=customBean1TxtProperty app.config.beans[2].name=customBean2ID app.config.beans[2].text=customBean2TxtProperty app.config.beans[3].name=customBean3ID app.config.beans[3].text=customBean4TxtProperty
Reading of a simple value can be done with @Value annotation.
@Value("${app.config.message}") private String message;
Using a value with annotation, lets see two examples.
@Autowired @Qualifier("${app.config.customBeanName}") DummyBean dummyBean; @Bean(name="${app.config.customBeanName}") public DummyBean dummyBean() { return DummyBean.builder().text("I am a dummy bean.").build(); }
Letting Spring map the properties automatically can be done with annotating the class with @ConfigurationProperties annotation.
@Configuration @EnableConfigurationProperties @PropertySource("classpath:application.properties") @ConfigurationProperties(prefix="app.config") // from properties, find all app.config* values public class AppPropertiesArray { private List<Bean> beans = new ArrayList<>(); public static class Bean { private String name; private String text; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public String toString() { return "Bean{" + "name='" + name + '\'' + ", text='" + text + '\'' + '}'; } } public List<Bean> getBeans() { return beans; } public void setBeans(List<Bean> beans) { this.beans = beans; } public List<Bean> getBeanList() { return beans; } }
Code is available at github.
There are more ways annotations can be used. Check docs and tutorials.
Spring Boot Docs – Externalizing configuration