TheMonkWhoSoldHisCode
TheMonkWhoSoldHisCode

Reputation: 2332

Inject spring beans based on a System Property

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

Upvotes: 2

Views: 1133

Answers (2)

luboskrnac
luboskrnac

Reputation: 24591

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.

Upvotes: 0

Mithun
Mithun

Reputation: 8077

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

Upvotes: 5

Related Questions