配置通常存储在属性或 XML 文件中,该文件放置在应用程序的运行时类路径中或指定为 VM 参数的固定位置。可以使用以下方式访问属性文件java.util.Properties http://java.sun.com/javase/6/docs/api/java/util/Properties.htmlAPI。可以使用 JAXP 或 JAXB 来解析 XML 文件。
以下是此类属性文件的示例:
jdbc.url = jdbc:mysql://localhost:3306/javabase
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = java
jdbc.password = d$7hF_r!9Y
假设它的名字是config.properties
并且它已放置在类路径的根目录中(或者其根路径已添加到类路径中),以下是从类路径加载它的方法:
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = properties.getProperty("jdbc.url");
String driver = properties.getProperty("jdbc.driver");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
// ...
以下是 XML 文件的示例:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<jdbc>
<url>jdbc:mysql://localhost:3306/javabase</url>
<driver>com.mysql.jdbc.Driver</driver>
<username>java</username>
<password>d$7hF_r!9Y</password>
</jdbc>
</config>
假设它被称为config.xml
它被放置在类路径的根目录中,下面是如何通过 JAXP 加载它的示例:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml");
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input));
XPath xpath = XPathFactory.newInstance().newXPath();
String url = (String) xpath.compile("//config//jdbc//url").evaluate(document, XPathConstants.STRING);
String driver = (String) xpath.compile("//config//jdbc//driver").evaluate(document, XPathConstants.STRING);
String username = (String) xpath.compile("//config//jdbc//username").evaluate(document, XPathConstants.STRING);
String password = (String) xpath.compile("//config//jdbc//password").evaluate(document, XPathConstants.STRING);
// ...
虽然只是更冗长一点JAXB https://stackoverflow.com/questions/5663581/parsing-a-simple-xml-document-with-jaxpjee6/5663786#5663786如果它是一个相当复杂的文件,可以让生活变得更轻松。
反过来,要在更高(操作系统/平台)级别控制对属性或 XML 文件的访问的安全。
也可以看看:
- 属性教程 http://java.sun.com/docs/books/tutorial/essential/environment/properties.html