如何在springboot中配置JNDI文件资源?

问题描述 投票:0回答:1

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

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

java spring spring-boot tomcat jndi
1个回答
0
投票

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);
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.