[英]JNDI configuration for Springboot standalone JAR application
我用 Springboot 创建了一个 JAR 应用程序。 我在 Tomcat 服务器下启动了这个 JAR 应用程序。
有人要求我使用 JNDI 检索存储在 Tomcat context.xml 中的数据源,说这很容易。
我尝试使用以下代码执行此操作。
Context initContext;
try {
initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/mydatabase");
} catch (NamingException e) {
System.out.println("ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
e.printStackTrace();
System.out.println("ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
但它不起作用。
我收到此错误:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
这是克服这个问题的简单方法吗?
或者用我的 JAR 独立应用程序,仍然绝对不可能克服这个问题,就像先例帖子Tomcat JNDI + Standalone Java通知?
我看到很多帖子,很多文档,但对我来说仍然不清楚。
谢谢你的帮助,你的分享。
托马斯
Kedar 给我一个答案。 我总结了 Kedar 的答案:
很抱歉延迟给出答案。
感谢 Kedar 告诉我 JNDI 不适用于 JAR,我尝试:
还要感谢 MKyong 的本教程: https://mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
这是我在 SpringBoot 下的工作代码:
@Configuration
public class ApplicationConfiguration {
/**
* Absolute path of the configuration file named context.xml on any Tomcat Server (DEV, TEST, PROD).
*/
private final String CONTEXT_XML_PATH_ON_SERVER = "/opt/tomcat/apache-tomcat-version/conf/context.xml";
@Bean
@Primary
public DataSource dataSource() {
try {
Element datasourceElement = getDatasourceElementInTomcatContextXml();
return DataSourceBuilder
.create()
.username(datasourceElement.getAttribute("username"))
.password(datasourceElement.getAttribute("password"))
.url(datasourceElement.getAttribute("url"))
.driverClassName(datasourceElement.getAttribute("driverClassName"))
.build();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException | IOException e) {
e.printStackTrace();
}
return null;
}
private Element getDatasourceElementInTomcatContextXml() throws ParserConfigurationException, SAXException, IOException {
File contextXmlFile = new File(CONTEXT_XML_PATH_ON_SERVER);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(contextXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
NodeList resourceElementList = doc.getElementsByTagName("Resource");
Node nNode = resourceElementList.item(0);
Element eElement = (Element) nNode;
return eElement;
}
}
感谢 Kedar 和 MKyong。
托马斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.