Java -- use DOM4J + Singleton mode to read XML files

Source: Internet
Author: User

Java -- use DOM4J + Singleton mode to read XML files

XML is a scalable markup language that is often used as a configuration file in projects. XML has high scalability. As long as you follow certain rules, the scalability of XML is almost unlimited, and this extension does not come at the cost of structure disorder or affect basic configuration. The rational use of the configuration file in the project can greatly improve the scalability of the system. Without changing the core code, you only need to change the configuration file to implement function changes, this also complies with the open and closed programming principles.

But how can we read data or information written to the configuration file from other classes or modules? At this time, we need to use the xml api. DOM4Jj is a very good JavaXML API with excellent performance, powerful functions and extremely easy to use features. Next we will take the java program to connect to the Oracle database as an example, a brief look at how to use the configuration file to improve program scalability and how DOM4J reads the configuration file.

Programs that do not use the configuration file

 

/** Encapsulate Common Database Operations */public class DbUtil {/** get connection */public static Connection getConnection () {Connection conn = null; try {Class. forName (oracle. jdbc. driver. oracleDriver); String url = jdbc: oracle: thin: @ localhost: 1525: bjpowernode; String username = drp1; String password = drp1; conn = DriverManager. getConnection (url, username, password);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}return conn ;}}
We can see that the DriverName, url, and other information in the above Code are all written in the Code. If the database information is changed, we must modify the DbUtil class, so the program scalability is extremely low, is not advisable.

 

We can save DriverName, url, and other information to the configuration file, so that if you modify it, you only need to modify the configuration file, and the program code does not need to be modified.

 

 
 
  
   
    oracle.jdbc.driver.OracleDriver
   
   
    jdbc:oracle:thin:@localhost:1525:bjpowernode
   
   
    drp1
   
   
    drp1
   
  
 
Then we need to create a configuration information class to access our attribute values.

 

 

/** Jdbc configuration information */public class JdbcConfig {private String driverName; private String url; private String userName; private String password; public String getDriverName () {return driverName ;} public void setDriverName (String driverName) {this. driverName = driverName;} public String getUrl () {return url;} public void setUrl (String url) {this. url = url;} public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} @ Overridepublic String toString () {// TODO Auto-generated method stubreturn this. getClass (). getName () + {driverName: + driverName +, url: + url +, userName: + userName + };}}

Next, use DOM4J to read XML Information and save the corresponding attribute values to JdbcConfig.

 

 

/** DOM4J + Singleton mode parse sys-config.xml file */public class XmlConfigReader {// lazy (delayed loading lazy) private static XmlConfigReader instance = null; // save jdbc-related configuration information private JdbcConfig jdbcConfig = new JdbcConfig (); private XmlConfigReader () {SAXReader reader = new SAXReader (); InputStream in = Thread. currentThread (). getContextClassLoader (). getResourceAsStream (sys-config.xml); try {Document doc = reader. read (in); // get jdbc-related configuration information Element driverNameElt = (Element) doc. selectObject (/config/db-info/driver-name); Element urlElt = (Element) doc. selectObject (/config/db-info/url); Element userNameElt = (Element) doc. selectObject (/config/db-info/user-name); Element passwordElt = (Element) doc. selectObject (/config/db-info/password); // sets jdbc-related configuration information jdbcConfig. setDriverName (driverNameElt. getStringValue (); jdbcConfig. setUrl (urlElt. getStringValue (); jdbcConfig. setUserName (userNameElt. getStringValue (); jdbcConfig. setPassword (passwordElt. getStringValue ();} catch (incluentexception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public static synchronized XmlConfigReader getInstance () {if (instance = null) {instance = new XmlConfigReader ();} return instance ;} /** return jdbc-related configuration */public JdbcConfig getJdbcConfig () {return jdbcConfig;} public static void main (String [] args) {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig (); System. out. println (jdbcConfig );}}

Then our database operation class can use the attribute values in the XML file.

 

 

/** Encapsulate Common Database Operations */public class DbUtil {/** get connection */public static Connection getConnection () {Connection conn = null; try {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig (); Class. forName (jdbcConfig. getDriverName (); conn = DriverManager. getConnection (jdbcConfig. getUrl (), jdbcConfig. getUserName (), jdbcConfig. getPassword ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}return conn ;}}

Now we can see that DriverName, url, and other information are directly obtained through jdbcConfig, and the data in jdbcConfig is XML read through DOM4J, in this way, we only need to modify the XML file through notepad to continue running the database information. This truly achieves the scalability of the program, so as to remain unchanged.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.