java - Spring Boot中如何配置JNDI文件资源?

标签 java spring spring-boot tomcat jndi

将WAS上运行的Spring应用程序迁移到嵌入tomcat的Springboot。

应用程序使用多个 jar 库来使用 jndi 加载文件。如何在我的 springboot 应用程序中配置类似于使用 jndi 加载文件的内容?

最佳答案

SpringBoot类:

@SpringBootApplication
@ComponentScan

public class BootApplication {
  @Value("${refEnv.url}")
  private String refEnvUrl;

  @Value("${refEnvironmentFile.jndi-name}")
  private String refEnvJNDI;

  public String getRefEnvUrl() {
    return refEnvUrl;
  }

  public void setRefEnvUrl(String refEnvUrl) {
    this.refEnvUrl = refEnvUrl;
  }

  public static void main(String[] args) {
    SpringApplication.run(BootApplication.class, args);
  }

  @Bean
  public ServletWebServerFactory servletContainer() {
    return new CustomTomcatServletWebServerFactory();
  }

  private class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {
    @Override
    protected void postProcessContext(Context context) {
      ContextResource refEnvFile = new ContextResource();
      refEnvFile.setName(refEnvJNDI);
      refEnvFile.setType(URL.class.getName());
      refEnvFile.setProperty("factory", "com.config.utils.URLFactory");
      refEnvFile.setProperty("file", refEnvUrl);
      context.getNamingResources().addResource(refEnvFile);
    }

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
      tomcat.enableNaming();
      TomcatWebServer container = super.getTomcatWebServer(tomcat);
      for (Container child : container.getTomcat().getHost().findChildren()) {
        if (child instanceof Context) {
          ClassLoader contextClassLoader = ((Context) child).getLoader().getClassLoader();
          Thread.currentThread().setContextClassLoader(contextClassLoader);
          break;
        }
      }
      return container;
    }
  }

}

URL 工厂类:

public class URLFactory implements ObjectFactory {
    public Object getObjectInstance(Object obj, Name name,
       Context nameCtx, Hashtable environment) throws Exception {
       Reference ref = (Reference) obj;
       String urlString = (String) ref.get("file").getContent();
       return new URL(urlString);
     }
}

关于java - Spring Boot中如何配置JNDI文件资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61672376/

相关文章:

java - 为什么我的 Spring Boot Web 应用程序无法在 Gradle 中完全运行?

java - 如果变量仅在作用域内使用,如何避免过早初始化

java - 禁用 ListView 中的项目 android java

java - 无法处理文件 - Android 工作室(应用程序 :mergeDebugResources)

java - 每当我尝试部署 Spring MVC 应用程序(从 Intellij 或通过将 war 文件复制到 webapps)时,Tomcat 7 都会显示状态 404

java - Maven 安装通过但测试失败

java - 前向 header 可变 Spring Boot

java - 在构造函数中使用派生类实例化基类引用

java - 动态定义在 Spring 中 Autowiring 哪个 bean(使用限定符)

java - Spring @Cacheable如何配置复杂的key