1

My project framework is designed in such a way that I don't have access to Springs ApplicationContext. However, I would like to inject beans based on a system property. If the property is set to true, then inject all the beans, else inject none. Is this a possibility. Something like the below. BTW, Spring version is 3.0

    <!-- all beans -->
      <bean></bean>
      <bean></bean>
      <bean></bean>
      <bean class ="org.springframework...PropertyPlaceHolderConfigurer>
        <property name = "properties"
          <value>
            OBJECT_INSTANCE_ID =0
          </value>
        </property>
     <bean>

In short the property is read using PropertyPlaceHolderConfigurer. All other beans should load based on value OBJECT_INSTANCE_ID. The property is defined in a property file located at /etc/../system.property

TheMonkWhoSoldHisCode
  • 2,182
  • 3
  • 26
  • 40

2 Answers2

5

You can use Spring profiles to achieve this functionality:

<beans profile="dev">
    <bean id="devConfig" class="<yourClassName>" />
</beans>

In the above example, the devConfig bean will be constructed only if dev profile is activated. You can activate a profile as follows:

Using annotations:

@ActiveProfiles("dev")

Using system property:

-Dspring.profiles.active=dev
Mithun
  • 7,747
  • 6
  • 52
  • 68
  • Profiles can still be used for your scenario. You can find different ways to set profile here - http://stackoverflow.com/questions/8587489/how-to-set-active-spring-3-1-environment-profile-via-a-properites-file-and-not-v – Mithun Mar 10 '15 at 05:33
0

If you would go for modern approaches like Java configs and Spring Boot, you can use @ConditionalOnProperty annotation that Spring Boot introduced as one of the conditional injections.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92