简体   繁体   中英

creating multiple instances of class with diffrent values using PropertyPlaceholderConfigurer in Spring

Can i create multipe instances of a class with multiple properties from multiple property files?

<beans>
   <bean class="xyz">
       <property name="abc">${abc}</property>
     <property name="pqr">${pqr}</property>
   </bean>
<beans>

Now I want to create number of beans for different values of abc and pqr

One xyz instance for one value of abc and pqr Second xyz instance for other value of abc and pqr

Can i do so using PropertyPlaceholderConfigurer?If yes , how?

Properties files usually don't contain duplicate keys. Therefore, I assume you have different files for each different 'abc' , 'pqr' key values, ie: you want to have one instance/one properties file. If so, then you can just load all the properties files and create the corresponding bean definitions like this:

<bean id="ppc1"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="classpath:/mya.properties" />
  <property name="placeholderPrefix" value="$a{" />
  <property name="placeholderSuffix" value="}" />
</bean>

<bean id="ppc2"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="classpath:/myb.properties" />
  <property name="placeholderPrefix" value="$b{" />
  <property name="placeholderSuffix" value="}" />
</bean>

<bean id="objectA" class="MyObject">
  <property name="field1" value="$a{abc}" />
  <property name="field2" value="$a{pqr}" />
</bean>

<bean id="objectB" class="MyObject">
  <property name="field1" value="$b{abc}" />
  <property name="field2" value="$b{pqr}" />
</bean>

Optionally create a 'container' bean which has a List<MyObject> instance variable. This will hold all of your MyObject instances:

<bean id="myContainerBean" class="MyContainer">
  <property name="objects">
    <list>
      <ref bean="objectA" />
      <ref bean="objectB" />
    </list>
  </property>
</bean>

If you think of a 'dynamic' solution then take @Biju's answer.

I can't think of anything out of the box - The only way that I can think of is to use a custom BeanFactoryPostProcessor . BeanFactoryPostProcessors allows you to add in more bean definitions as the application context is being loaded up, so you can write a custom code which registers more bean definitions based on your property files and they will manifest as beans at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM