java - springboot中如何配置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);
}
}
推荐阅读
- python - 两个for循环的优化
- gradle - 没有可用于离线模式的 com.android.tools.build:aapt2:3.6.1-6040484 缓存版本
- python - 如何从列表的每个元素中创建一个变量?
- java - 添加(索引,元素)方法
- php - 升级PHP后出现错误非法字符串偏移
- javascript - 如何在 React native 的 API url 中传递变量?
- python - 使用 matplotlib.pyplot 和 numpy 在 python 中显示 Mandelbrot 集
- php - 在 XAMPP(MacOS)中使用 php 连接 MySQL 服务器被拒绝连接
- javascript - 将资产管道处理的 javascript 文件的内容插入 HTML
- callback - 谷歌 recaptcha v2 突然不会响应成功