有没有办法在applicationContext.xml文件中启用或禁用Spring bean定义? [英] Is there any way to enable or disable the Spring bean definition in applicationContext.xml file?

查看:453
本文介绍了有没有办法在applicationContext.xml文件中启用或禁用Spring bean定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序上下文中有没有办法启用禁用 java bean定义?

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>

或者,有没有办法加载应用程序中定义的bean 有条件背景?

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

推荐答案

有一项新功能 @Profile 将在春季3.1中完成工作

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

来自此处


Spring 3.1引入了环境配置文件的概念。一个常见的
用例是设置
开发,QA和生产环境之间不同的bean。一个典型的例子是
与开发中的独立DataSource相比,而不是在生产中从JNDI查找
的DataSource。另一个例子是用于分析的bean
配置文件,可以轻松打开或关闭。您可以在XML中的beans元素上添加
profile属性,或在代码中添加@Profile
annotation。请注意,可以将Spring bean分配给
多个配置文件。

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 {
    ...
}




这些配置文件可以通过spring.profiles.active
属性激活,该属性可以通过环境变量,JVM
系统指定property,web.xml或JNDI中的Servlet。这些
配置文件也可以使用
Environment.setActiveProfiles(String ...)通过代码激活。为了使bean配置文件正常工作,现在允许在Spring XML中使用
嵌套bean元素,尽管
仅限于文件末尾。请注意,建议
使您的bean拓扑尽可能在环境之间保持接近,因此
您的应用程序可以跨环境进行适当测试。您还
使用Environment.containsProperty()方法在不同的属性源中搜索属性
。此属性解析还
适用于XML bean定义中的$ {placeholder}变量。

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.

这篇关于有没有办法在applicationContext.xml文件中启用或禁用Spring bean定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆