如何用Spring 3.1的Environment和Profile简化工作

2025-03-23 05:21:24
推荐回答(1个)
回答1:

Spring 3.1为这个问题提供了一个解决方案(如果你还没有为自己的项目升级Spring版本,嗯,你麻烦大了)。
Spring在容器中引入Environment和Profile的概念。每个应用程序上下文都有一个都可以访Environment对象。
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext();
ConfigurableEnvironment configurableEnvironment =
classPathXmlApplicationContext.getEnvironment();
每种运行环境都有很多活动Profile类可供使用。大多数讲解Spring Profile的例子都是在开发模式或生产模式下。对于不同运行环境问题来说,我的解决方案是使用使用多个Profile来适应不同运行时。这个解决方案的优势是你可以自行决定如何使用Profile。
默认星空情况下,你所创建的Bean在载入容器中后是没有Profile对象的。下面看一个例子。假设下面是我的应用程序中,数据源实例的定义。


class="org.apache.commons.dbcp.BasicDataSource">