2017-02-15 127 views
2

將非Spring應用程序轉換爲Spring Boot時,希望在嵌入式tomcat中使用現有的context.xml文件。閱讀Spring Boot中的context.xml嵌入式Tomcat

使用Spring 1.5.1引導和Tomcat 8.5.11

TomcatEmbeddedServletContainerFactory配置

@Bean 
public TomcatEmbeddedServletContainerFactory tomcatFactory() { 
    return new TomcatEmbeddedServletContainerFactory() { 

     @Override 
     protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) { 
      tomcat.enableNaming(); 
      return super.getTomcatEmbeddedServletContainer(tomcat); 
     } 

     @Override 
     protected void postProcessContext(Context context) { 
      // Try-1 - Not Working 
      if (context instanceof StandardContext) { 
       StandardContext standardContext = (StandardContext) context; 
       standardContext.setCopyXML(true); 
      } 

      // Try-2 - Not Working 
      context.setConfigFile(Paths.get("/META-INF/context.xml").toFile().toURI().toURL()); 

      // Try-3 - Working - But due to very large and multiple configuration, java config will be cumbersome 
      ContextResource resource = new ContextResource(); 
      resource.setName("jdbc/myDB"); 
      resource.setType(DataSource.class.getName()); 
      resource.setAuth("Container"); 
      resource.setProperty("username", "user111"); 
      resource.setProperty("password", "password111"); 
      resource.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver"); 
      context.getNamingResources().addResource(resource); 
     } 
} 

方法用於檢查數據庫連接,

public void checkDb() { 
    Context initContext = new InitialContext(); 
    Context envContext = (Context) initContext.lookup("java:/comp/env"); 
    DataSource datasource = (DataSource) envContext.lookup("jdbc/myDB"); 
    Connection con = datasource.getConnection(); 
} 

那麼如何加載在現有的context.xml春季啓動。

回答

0

我想你可以配置路徑到Tomcat目錄,並用它在春季啓動 spring doc with embedded container

+0

我也嘗試添加server.tomcat.basedir =目標/ tomcat的在application.properties並添加上下文的變體。 xml在conf目錄中,但沒有幫助。 – Sheel