首页 > 解决方案 > springboot中如何配置JNDI文件资源?

问题描述

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

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

标签: javaspringspring-boottomcatjndi

解决方案


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

推荐阅读