Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a dynamic property list into a spring managed bean

I've been searching but cannot find these steps. I hope I'm missing something obvious.

I have a properties file with the following contents:

machines=A,B 

I have another file like that but having a different number of members in the machines element like this:

machines=B,C,D 

My question is how do I load this variable-length machines variable into a bean in my spring config in a generic way?

something like this:

<property name="machines" value="${machines}"/> 

where machines is an array or list in my java code. I can define it however I want if I can figure out how to do this.

Basically I'd rather have spring do the parsing and stick each value into a list element instead of me having to write something that reads in the full machines string and do the parsing myself (with the comma delimiter) to put each value into an array or list. Is there an easy way to do this that I'm missing?

like image 445
bob Avatar asked Mar 11 '11 14:03

bob


People also ask

How do you inject configuration values from the properties file into beans?

Property values can be injected directly into your beans by using the @Value annotation, accessed through Spring's Environment abstraction, or be bound to structured objects through @ConfigurationProperties .

How do you load and inject properties into a spring bean?

Spring Bean + Properties + Annotation configuration example Create a configuration class and define the properties bean in it as shown below. Create a spring bean class and inject properties into it using @Autowired and @Qualifier annotations. Create main class and run application.


2 Answers

You may want to take a look at Spring's StringUtils class. It has a number of useful methods to convert a comma separated list to a Set or a String array. You can use any of these utility methods, using Spring's factory-method framework, to inject a parsed value into your bean. Here is an example:

<property name="machines">     <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">         <constructor-arg type="java.lang.String" value="${machines}"/>     </bean> </property> 

In this example, the value for 'machines' is loaded from the properties file.

If an existing utility method does not meet your needs, it is pretty straightforward to create your own. This technique allows you to execute any static utility method.

like image 72
Kris Babic Avatar answered Sep 21 '22 08:09

Kris Babic


Spring EL makes easier. Java:

List <String> machines; 

Context:

<property name="machines" value="#{T(java.util.Arrays).asList('${machines}')}"/> 
like image 38
Jingyang Peng Avatar answered Sep 22 '22 08:09

Jingyang Peng