在Spring Boot Embedded Tomcat中读取context.xml

时间:2017-02-15 10:57:45

标签: java spring-boot tomcat8 embedded-tomcat-8

将非Spring应用程序转换为Spring Boot时,希望在嵌入式tomcat中使用现有的context.xml文件。

使用Spring Boot 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();
}

那么如何在Spring Boot中加载现有的context.xml。

1 个答案:

答案 0 :(得分:0)

我认为作为变种,您可以配置tomcat目录的路径并在spring boot中使用它 spring doc with embedded container