Explain Codes LogoExplain Codes Logo

Reading a List from Properties File and Load with Spring Annotation @Value

java
spring-boot
configuration-properties
autowiring
Nikita BarsukovbyNikita BarsukovΒ·Dec 15, 2024
⚑TLDR

Need to load a list from a properties file into a Spring bean? Easy! Define the list as a comma-separated values and join forces with @Value and Spring Expression Language to ensure smooth loading:

# application.properties listItems=Item1,Item2,Item3
// Your Spring Bean @Component public class Config { @Value("#{'${listItems}'.split(',')}") private List<String> values; // πŸŽ‰ Boom! An elegant list from a single line }

Thus, @Value and SpEL transform the comma-separated string into a handy Java List.

Nuts and Bolts of loading Lists

Behind the one-liner magic of @Value and Spring Expression Language (SpEL) is a simple principle. Tap into its power with .split(',') β€” this SpEL function turns a string into an array, which is then transposed into a List<String> by our Spring knights in shining armor.

Loading of properties file, marks the beginning of this journey. Place it under src/main/resources in any Maven/Gradle project. Our beloved @PropertySource, if being used, must have the location and name of the file correctly mentioned.

Upgrade your Configurations with ConversionService

Consider ConversionService as the upgrade to first class in your Spring journey. Registering it in the Spring context, you gain control over the conversion process, even catering to whitespaces and custom delimiters.

@Bean public ConversionService conversionService() { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); bean.afterPropertiesSet(); // Here's our bean, all cooked and served hot! return bean.getObject(); }

Power-up with @ConfigurationProperties

The mighty @ConfigurationProperties provides a type-safe way to load configuration properties directly into an object. A great tool in our Spring Boot toolbox.

@Component @ConfigurationProperties(prefix = "email") public class EmailProperties { private List<String> admins; // Ready to boss the email world! // Getters and Setters }

Unleashing power with Autowiring

Pair @Autowired with @Component and @ConfigurationProperties, and the properties will be effortlessly tied to your bins.

Spring Boot Magic with Metadata

Going for Spring Boot configurations? Place settings within META-INF/spring.factories to let Spring Boot auto-configure, like a fairy godmother to Cinderella!

When Properties seem elusive

If properties fights back, remember:

  • Look out for @PropertySource. Ensure the path is in place.
  • application.properties or application.yml must be correctly positioned.
  • Have an eagle eye on the key in @Value. It should match your properties file key perfectly – no less, no more!