用于在 Java 中保存连接字符串参数的配置文件
我来自 ASP .Net 背景.我现在正在编写一个 Java 程序来将数据从 DB2 数据库导入 Oracle 数据库.我已经完成了导入这些数据的基本功能.
I come from an ASP .Net background. I am now writing a Java program to import data from a DB2 database into an Oracle database. I have completed the basic functionality of importing this data.
我的问题是,我将所有连接属性都硬编码到 Java 程序本身中.是否有任何最佳实践"方法可以将连接字符串详细信息存储在类似于我们用于 ASP .Net 的 web.config 的配置文件中?Java 是否有任何机制来实现这一点?还是我需要简单地使用 I/O 操作从一个简单的 txt 文件中读取键/值对?我读过一些关于 .properties 的内容?这是要走的路吗?
The problem I have is, I have all the connection properties harcoded into the Java program itself. Is there any "Best Practices" methodology to have the connection string details stored in a configuration file similar to web.config we use for ASP .Net? Does Java have any kind of mechanism for accomplishing this? Or do I need to simply use I/O operations to read the key/value pairs from a simple txt file? I have read a bit about .properties? Is this this way to go?
我只是在寻找正确的方向.任何帮助将不胜感激.
I am just looking for a prod in the right direction. Any help would be appreciated.
推荐答案
如果您不依赖于特定框架,最简单的方法是使用属性文件.查看this question的已接受答案的后半部分(不是您的情况的 XML 位).
The simplest way to do it, if you're not tied to a particular framework, is with a properties file. Have a look at the latter part of the accepted answer for this question (not the XML bit for your case).
根据您是否使用 servlet 容器或类似容器(例如 Tomcat、Glassfish 等),您可能还希望考虑使用该容器的连接设置和连接池,这可能比回收您自己的连接更简单.
Depending on whether you're using a servlet container or similar (e.g. Tomcat, Glassfish, etc.), you may also wish to consider using that container's connection settings and connection pooling, which may be simpler than recycling your own connections.
但是,如果您只是想尝试进入 Java 并且这是为了让您了解 JDBC,请先保持简单,然后从类路径上的 db.properties 文件中读取您的属性.
But if you're just trying to feel your way into Java and this is for you to learn about JDBC, keep it simple initially and just read your properties from a db.properties file on your classpath.
相关文章