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

2025-03-23 06:17:15
推荐回答(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">






在Spring 3.0中,增加了一个新的容器类GenericXmlApplicationContext ,可以作为ClassPathXmlApplicationContext和FileSystemXmlApplicationContext之外的另一个选择。

GenericXmlApplicationContext类的特点是可以通过Setter方法完成所有的配置,而无需依靠笨重的构造器去完成配置。记住,在初始化容器的准备工作完成后,需要调用refresh()方法完成实际的初始化工作。

下面的代码展示了如何使用GenericXmlApplicationContext类初始化容器:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("standalone");
ctx.load("*Context.xml");
ctx.refresh();

这里,我将活动Profile设置为“standalone”。在这个工程里,我希望代码既可以作为“standalone”运行在应用程序容器之外,还可以作为“container”运行在容器中。这里,我可以设置多个Profile,例如,下面的代码设置了Profile为“standalone”与“activemq”。

1
ctx.getEnvironment().setActiveProfiles("standalone", "activemq");
虽然做了上面的配置,实际上并不会对当前的配置上下文产生影响,因为还没有配置Profile实例。所以,修改配置上下文为:



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






只有当活动Profile设置为“standalone”时,才会实例化这个Bean。Profile是Bean的属性,而不是一个实例对象,因此,你无法配置单独的Bean来选择Profile。在较早的Spring版本中,这会导致产生多个文件,而Ant的通配符无法在运行时找到正确的配置文件。

在Spring 3.1中,标签可以嵌套在标签内。现在,我们重新编写一下数据源配置文件:
















这样,就可以通过下面的代码快速切换Profile:

ctx.getEnvironment().setActiveProfiles("container");

另一种切换Profile的方法是在运行时作为系统参数传入:
-Dspring.profiles.active="standalone"

此外,也可以作为Ear/War的初始化参数传入:


dispatcher

org.springframework.web.servlet.DispatcherServlet


spring.profiles.active
production