简体   繁体   中英

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

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

如果您要使用Java配置和Spring Boot等现代方法,则可以使用Spring Boot作为条件注入之一引入的@ConditionalOnProperty批注

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