1. 程式人生 > >spring 設定通過程式碼啟動載入配置檔案和設定啟動順序

spring 設定通過程式碼啟動載入配置檔案和設定啟動順序



通過這種方式載入可以使用maven模組化,拋開web.xml的束縛。

@Order(1)
public class SpringConfigInitializer extends AbstractContextLoaderInitializer
  implements WebApplicationInitializer
{
  protected WebApplicationContext createRootApplicationContext()
  {
    String allXml = getRootContextConfigLocation();
    XmlWebApplicationContext s = new XmlWebApplicationContext();
    s.setConfigLocation(allXml);
    return s;
  }


  public String getRootContextConfigLocation() {
    String configLocationParam = "classpath:config/bomf/spring/applicationContext.xml";
    Properties props = StrTool.getProperties("/config/bomf/dssp.properties");
    boolean webOnly = 
      Boolean.valueOf(props
      .getProperty("webOnly", "false")).booleanValue();


    if (!webOnly) {
      configLocationParam = configLocationParam + ",classpath:config/bomf/server/*.xml";
    }
    else {
      configLocationParam = configLocationParam + ",classpath:config/bomf/client/*.xml";
    }


    boolean jaxws = Boolean.valueOf(props.getProperty("jaxws", "false")).booleanValue();
    if (jaxws) {
      configLocationParam = configLocationParam + ",classpath:config/bomf/spring/jax-ws.xml";
    }


    boolean hessianConsumer = Boolean.valueOf(props.getProperty("hessianConsumer", "false")).booleanValue();


    if (hessianConsumer) {
      configLocationParam = configLocationParam + ",classpath:config/bomf/spring/hessian-comsumer.xml";
    }


    String cacheProvider = props.getProperty("cache.provider", "ehcache");
    configLocationParam = configLocationParam + ",classpath:config/bomf/spring/application-cache-" + cacheProvider + ".xml";


    boolean dubbo = Boolean.valueOf(props.getProperty("dubbo", "false")).booleanValue();


    if (dubbo) {
      configLocationParam = configLocationParam + ",classpath:config/bomf/spring/dubbo.xml";
    }


    if (!webOnly) {
      boolean isJndi = Boolean.valueOf(props.getProperty("isJndi", "false")).booleanValue();


      if (isJndi) {
        configLocationParam = configLocationParam + ",classpath:config/bomf/spring/jndi_db.xml";
      }
      else {
        configLocationParam = configLocationParam + ",classpath:config/bomf/spring/c3p0_db.xml";
      }
    }


    String otherspringxml = props.getProperty("otherspringxml");
    if (StrTool.isValid(otherspringxml)) {
      configLocationParam = configLocationParam + "," + otherspringxml;
    }
    String securityType = props.getProperty("securityType", "spring");
    if ((StrTool.isValid(securityType)) && (!"none".equals(securityType))) {
      configLocationParam = configLocationParam + ",classpath:config/bomf/spring/" + securityType + "-security.xml";
    }


    return configLocationParam;
  }
}