Home >Java >javaTutorial >How to Read a List from a Spring Properties File using @Value?

How to Read a List from a Spring Properties File using @Value?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 14:57:16351browse

How to Read a List from a Spring Properties File using @Value?

Reading a List from Properties File with Spring Annotation @Value

In Spring, loading a list of values from a properties file can be achieved using the @Value annotation. This annotation allows for direct injection of property values into fields or methods.

To load a comma-separated list like my.list.of.strings=ABC,CDE,EFG from a properties file into a list of strings, use the following annotation:

@Value("${my.list.of.strings}")
private List<String> myList;

This will automatically populate the myList field with the values from the properties file. Note that the property file must be loaded correctly in your Spring configuration.

However, if the values are not comma-separated or require more complex parsing, an alternative approach is to load the property as a String and manually split it into a list:

@Value("${my.list.of.strings}")
private String commaSeparatedList;

@PostConstruct
private void init() {
    myList = Arrays.asList(commaSeparatedList.split(","));
}

The above is the detailed content of How to Read a List from a Spring Properties File using @Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn