Home > OS >  how can I parametrize the spring constructor-arg injection based on the property file or environment
how can I parametrize the spring constructor-arg injection based on the property file or environment

Time:02-04

I have the following constructor in my spring application:

<bean id="metadata" >
    <constructor-arg>
        <list>
            <bean >
                <constructor-arg>
                    <bean >
                        <constructor-arg>
                            <value type="java.io.File">classpath:metadata/idp-test.xml</value>
                        </constructor-arg>
                        <property name="parserPool" ref="parserPool"/>
                    </bean>
                </constructor-arg>
                <constructor-arg>
                    <bean />
                </constructor-arg>
            </bean>
        </list>
    </constructor-arg>
</bean>

Now, I have 2 different xml config files, one for test env and one for prod env. Is there a way in the config above to have some kind of switch (or if-else perhaps?), based on which there would be either the idp-test.xml or a different one idp-prod.xml injected? I assume it would be based on the property file or e.g. environmental variable, that would store the info which environment is it (test or prod).

CodePudding user response:

Are you looking for the profile feature which allow you to enable a bean only if certain profile is activated ?

If yes, you can first configuring a profile for the bean :

<beans profile="prod">
  <bean id="metadata" >
  </bean>
</bean>

<beans profile="test">
  <bean id="metadata" >
  </bean>
</bean>

And activating a particular profile by configuring the JVM system property spring.profiles.active in the command that start JVM :

 -Dspring.profiles.active="prod"

Or activate from the environment variable:

export spring_profiles_active=prod

In this case , only the bean with prod profile and without specifying any profile will be enabled.

  •  Tags:  
  • Related