有条件地在XML ArrayList中包含bean

Jan*_*ert 3 java xml spring

我想知道是否有可能根据某些属性有条件地包括春豆。

在我applicationContext.xml的清单中,我列出了我设置的bean:

<bean id="server1Config" class="... />
<bean id="server2Config" class="... />
<bean id="server3Config" class="... />
...
Run Code Online (Sandbox Code Playgroud)

然后将它们包括在列表中:

<bean class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <ref bean="server1Config"/>
                <ref bean="server2Config"/>
                <ref bean="server3Config"/>
                ...
            </list>
    </constructor-arg>
</bean>
Run Code Online (Sandbox Code Playgroud)

我想有条件包括server1Config,server2Config,server3Config等取决于是否${includeServer1} == true${includeServer2} == true等等,如果可能的话,只有当他们被标记为包含初始化这些豆子。

澄清一下,它是ping服务,用于检查服务器是否在线,每个bean都包含特殊的url。如果我有5台服务器正在运行,我想在我的配置中设置includeServer1=true... includeServer5=true... includeServer6=false,如果我关闭server2,我想先更改includeServer2 = false,然后再关闭服务器,以免被SMSe告知server2离线。

swi*_*ler 5

由于您的名字指的是不同的阶段或环境,因此弹簧轮廓可能会有所帮助。您可以在context.xml中定义这样的bean

<beans profile="dev">
    <jdbc:embedded-database id="dataSource">
        <jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
        <jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
    </jdbc:embedded-database>
</beans>

<beans profile="production">
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

在示例[1]中,您将看到两个配置文件“ dev”和“ production”的用法。

  • Spring将始终加载每个没有配置文件的bean
  • 根据概要文件(是的,您可以一次加载多个概要文件),将加载所有相关的Bean

用Java加载配置文件:

ctx.getEnvironment().setActiveProfiles("dev");
Run Code Online (Sandbox Code Playgroud)

加载两个配置文件

ctx.getEnvironment().setActiveProfiles("profile1", "profile2");
Run Code Online (Sandbox Code Playgroud)

从CMD Line声明式加载:

-Dspring.profiles.active="profile1,profile2"
Run Code Online (Sandbox Code Playgroud)

在web.xml中的用法(可以用逗号分隔)

  <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>spring.profiles.active</param-name>
          <param-value>production</param-value>
      </init-param>
  </servlet>
Run Code Online (Sandbox Code Playgroud)

@Comment:如果要使用属性来做,并且能够使用较新的spring元素,注释等,请查看本教程[2],使其与属性文件一起使用,如下所述。

[1] http://spring.io/blog/2011/02/11/spring-framework-3-1-m1-released/ [2] http://kielczewski.eu/2013/11/setting-active- Spring MVC中的配置文件和属性来源/