【问题标题】:How to configure JNDI File resource in springboot?如何在 Spring Boot 中配置 JNDI 文件资源?
【发布时间】:2020-08-23 14:38:45
【问题描述】:

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

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

【问题讨论】:

标签: java spring spring-boot tomcat jndi


【解决方案1】:

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);
     }
}

【讨论】:

    猜你喜欢
    • 2016-07-12
    • 2016-10-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多