java - 读取Spring Boot嵌入式Tomcat中的context.xml

标签 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。

最佳答案

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

关于java - 读取Spring Boot嵌入式Tomcat中的context.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42247396/

相关文章:

java - 如何忽略 Okhttp 中的 SSL 错误?

java - 使用 google 电子表格 api 下载 google 电子表格

java - Spring Boot Hibernate+Mysql问题

java - 如何返回不是实体的对象列表并添加一个自定义变量,该变量将从 hibernate 查询中的属性文件中获取?

java - 忽略列表中对象的特定属性

java - Tomcat 8.5.15 无法找到 jcifs.jar

java - 在select sql语句中将参数设置为null

java - 线程 :Snake game 中出现异常

java - log4j2线程的Tomcat内存泄漏问题

tomcat-users.xml 在停止 Tomcat 8 后重置