Is there any way to enable or disable the Spring b

2020-02-06 00:40发布

问题:

Is there any way to enable or disable a java bean definition in application context?

<bean id="enBean" classs="com.en.bean.BeanName">
   <property name="prop1"/>
</bean>

Or, is there any way to load the bean conditionally defined in application context?

回答1:

There is a new feature @Profile in spring 3.1 that would do the job

From here

Spring 3.1 introduces the concept of environment profiles. A common use case is the setting up of beans that are different between development, QA and production environments. A typical example is going against a standalone DataSource in development versus looking up the DataSource from JNDI in production. Another example is a beans profile for profiling that can easily be turned on or off. You can add a profile attribute on a beans element in XML or add @Profile annotation in code. Note that a Spring bean can be assigned to multiple profiles.

<beans profile="dev">
    ...
</beans>
@Profile("dev")
public class Bean {
    ...
}

These profiles can be activated through the spring.profiles.active property which may be specified through an environment variable, a JVM system property, a Servlet in web.xml or JNDI. These profiles can also be activated through code using Environment.setActiveProfiles(String ...). To make bean profiles work, nested beans elements are now allowed in the Spring XML, although constrained only at the end of the file. Note that it's recommended to keep your bean topology as close as possible between environments, so your application gets properly tested across environments. You also use the Environment.containsProperty() method to search for properties across the different property sources. This property resolution also works for ${placeholder} variables in XML bean definitions.