Single column mode - write class ConfigManager to read properties file

 
database.properties :--->
  jdbc.driver_class=com.mysql.jdbc.Driver
  jdbc.connection.url=jdbc:mysql://127.0.0.1:3306/news?useUnicode=true$characterEncoding=utf8-8
  jdbc.connection.username=root
  jdbc.connection.password=1234
 
========Singleton Mode==========: There is one and only one instance during runtime
 key point:
  1. A class has only one instance -- the most basic -- (provides only a private constructor)
  2. It must create this instance by itself -- (defines a static private object of the class)
  3. It must provide this instance to the entire system by itself -- (provide a static public method that returns a static private object that creates or obtains itself)
 -----------------------------------------------------------
  Lazy mode: (thread is not safe, in a concurrent environment, it is very likely that there will be multiple configManager instances ------
------------- Need to consider synchronization 1. Method body plus synchronization synchronized 2. Double check lock)
     When the class is loaded, the instance is not created, it is created when the call is run.
    Advantage: fast class loading
    Disadvantages: inefficient, slow to get objects at runtime
 -----------------------------------------------------------
   Hungry mode: (thread safe)
          The initialization is done when the class is loaded.
          So class loading is slow, but fetching objects at runtime is fast
    1. as written in this way
private static ConfigManager configManager2 = new ConfigManager();
    2. Or write like this
private static ConfigManager configManager;
static(){
    configManager = new ConfigManager();
}

  3. If there is a requirement to implement lazy loading, use static inner classes;

     Guaranteed class loading speed

--(When the test() method is called externally, the static inner class implements lazy loading)

 

public class Singleton {
	// static inner class lazy loading
	private static Singleton singleton;
	
	private Singleton(){}
	
	private static class SingletonHelper{
		private static final Singleton INSTANCE = new Singleton();
	}
	
	public static Singleton getInstance(){
		return SingletonHelper.INSTANCE;
	}
	
	public static void test(){
		System.out.println("test===" + singleton.toString());
	}
	
}

 

 

----------------------------------------------------------------------

 

database.properties :--->   jdbc.driver_class=com.mysql.jdbc.Driver   jdbc.connection.url=jdbc:mysql://127.0.0.1:3306/news?useUnicode=true$characterEncoding=utf8-8   jdbc.connection.username=root   jdbc.connection.password=1234
 
========Singleton Mode==========: There is one and only one instance during runtime
 key point:
  1. A class has only one instance -- the most basic -- (provides only a private constructor)
  2. It must create this instance by itself -- (defines a static private object of the class)
  3. It must provide this instance to the entire system by itself -- (provide a static public method that returns a static private object that creates or obtains itself)
 -----------------------------------------------------------
  Lazy mode: (thread is not safe, in a concurrent environment, it is very likely that there will be multiple configManager instances ------
------------- Need to consider synchronization 1. Method body plus synchronization synchronized 2. Double check lock)
     When the class is loaded, the instance is not created, it is created when the call is run.
    Advantage: fast class loading
    Disadvantages: inefficient, slow to get objects at runtime
 -----------------------------------------------------------
   Hungry mode: (thread safe)
          The initialization is done when the class is loaded.
          So class loading is slow, but fetching objects at runtime is fast
    1. as written in this way
private static ConfigManager configManager2 = new ConfigManager();
    2. Or write like this
private static ConfigManager configManager;
static(){
    configManager = new ConfigManager();
}

  3. If there is a requirement to implement lazy loading, use static inner classes;

     Guaranteed class loading speed

--(When the test() method is called externally, the static inner class implements lazy loading)

 

public class Singleton {
	// static inner class lazy loading
	private static Singleton singleton;
	
	private Singleton(){}
	
	private static class SingletonHelper{
		private static final Singleton INSTANCE = new Singleton();
	}
	
	public static Singleton getInstance(){
		return SingletonHelper.INSTANCE;
	}
	
	public static void test(){
		System.out.println("test===" + singleton.toString());
	}
	
}

 

 

----------------------------------------------------------------------

 

  ========Singleton mode==========: There is only one instance during runtime Key points:
  1. A class has only one instance -- the most basic -- (provides only a private constructor)
  2. It must create this instance by itself -- (defines a static private object of the class)
  3. It must provide this instance to the entire system by itself -- (provide a static public method that returns a static private object that creates or obtains itself)
 -------------------------------------------------- --------- Lazy mode: (thread is not safe, in a concurrent environment, it is very likely that there will be multiple configManager instances ------ ------------- Required Consider synchronization 1, method body plus synchronization synchronized 2, double check lock) When the class is loaded, the instance is not created, and it is created when the call is run. Advantages: fast class loading Disadvantages: low efficiency, slow to obtain objects at runtime --------------------------------- -------------------------- Hungry mode: (thread safe)
          The initialization is done when the class is loaded.
          So class loading is slow, but fetching objects at runtime is fast
          The initialization is done when the class is loaded. So class loading is slow, but getting objects at runtime is fast
private static ConfigManager configManager2 = new ConfigManager();
    2. Or write like this
private static ConfigManager configManager;
static(){
    configManager = new ConfigManager();
}
-----------------------------------------------------------------------
 

package cn.news.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

//Tool class for reading configuration files -- singleton mode
public class ConfigManager {
	//Read the configuration file properties.load(inputstream);
	private static ConfigManager configManager;
	private static Properties properties;
	private ConfigManager(){
		String configFile="database.properties";
		properties = new Properties();
		InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
		try {
			properties.load(is);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	}
	
	public static ConfigManager getInstance(){
		if(configManager==null){
			configManager = new ConfigManager();
		}
		return configManager ;
	}
	
	//Get the value corresponding to the key;
	public String getString(String key){
		return properties.getProperty(key);
	}
}

 ================================================================================

 

=================================================================================

package com.news.util;
import java.io.InputStream;
import java.util.Properties;
/**
 *
 * *Tool class for reading configuration files---single-column mode---lazy mode---lazy loading
 *
 * Steps:
 *
 * 1. Create a private constructor to read the configuration file
 * 2. Create a global access point, set the number of serializations through the single-column mode, and return the configManager instance
 * 3. Obtain the corresponding value through the key
 */
public class ConfigManager {

    private static ConfigManager configManager;
    private static Properties properties;//Properties is used to operate the properties file
    
    //Private constructor to read the configuration file
    private ConfigManager(){
        String configFile="jdbc.properties";
        properties=new Properties();
        
    try {
        //find resources through classpath
        //Find the corresponding configFile file in the root directory of the package where the current class is located
        //getClassLoader() returns the class loader
        //getResourceAsStream(configFile) returns the InputStream object
        InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
        properties.load(is);//Read the configuration file
        is.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    }
    
    /*
     *Thread-insecure, in a concurrent environment, it is very likely that multiple configManager instances will appear
     *Need to consider synchronization, you can add synchronization lock synchronized
     * Lazy mode (thread unsafe - solution 1. Method body plus synchronization lock synchronized 2. Double check lock)
     * The instance column is not created when the class is loaded, it is created at runtime.
     * Advantage: fast class loading
     * Disadvantages: low efficiency, slow to obtain objects at runtime
     *
     *
     */
    //global access point
    //Set the number of serialization through single-column mode
    public static synchronized ConfigManager getInstance(){
        if (configManager==null) {
            configManager=new ConfigManager();
        }
        return configManager;
    }
    //Get the corresponding value by key
    public String getValue(String key){
        return properties.getProperty(key);
    }
        
    
    /*//Double check lock
     public static ConfigManager getInstance(){
            if (cManager==null) {
                synchronized(ConfigManager.class){
                    if (cManager==null) {
                        cManager=new ConfigManager();
                    }
                }
            }
            return cManager;
        }*/
}

 ===================================================================================================

===================================================================================================

package com.news.util;
import java.io.InputStream;
import java.util.Properties;
/**
 * Single-column mode---Hungry mode: (thread safe)
The initialization is done when the class is loaded. So class loading is slow, but fetching objects at runtime is fast
 */
public class ConfigManager2 {  
    //When the class is loaded, it is automatically initialized
    private static ConfigManager2 configManager2=new ConfigManager2();
    private static Properties properties;  
    // private constructor
    private ConfigManager2(){
        String configFile="database.properties";
        properties=new Properties();     
    try {
        //find resources through classpath
        //Find the corresponding configFile file in the root directory of the package where the current class is located
        InputStream is=ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
        properties.load(is);
        is.close();
    } catch (Exception e) {
    }   
    }

    //global access point
    public static ConfigManager2 getInstance(){
        return configManager2;
    }
    
    public String getValue(String key){
        return properties.getProperty(key);
    }    
}

 --------------------------------------------------------------------------------------------------------------------------------------

The above tool class is used when JDBC connects to the database. The tool class creates the configManager instance column and obtains the database connection through the configManager instance column.

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.util.ConfigManager;

/*
 * Base class for operating database --- static class
 *
 * method:
 * 1. Get database connection: public static Connection getConnection()
 * Steps:
 * Get the value of the porperties file
 * Load class driver
 * get connection
 * return connection
 *
 * 2.查询操作:public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params)
            throws SQLException
                    step:
                        execute SQL
                        receive result set
                        return result set
    3.更新操作:    public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params)
            throws Exception
                    step:
                        execute SQL
                        Number of rows affected
                        Returns the number of rows affected
    4.关闭资源:public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet)
 * Steps:
 * close resource
 * GC recovery
 * return falg
 */
public class BaseDao {

    //get database connection
    public static Connection getConnection(){
        String driver=ConfigManager.getInstance().getValue("driver");
        String url=ConfigManager.getInstance().getValue("url");
        String username=ConfigManager.getInstance().getValue("username");
        String password=ConfigManager.getInstance().getValue("password");

        Connection connection=null;

        //class loading

        try {
            Class.forName(driver);
            connection=DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        }
        return connection;

    }


    //close the resource
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag=true;
        if (resultSet!=null) {
            try {
                resultSet.close();
                resultSet=null;//GC recovery
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace ();
                flag=false;
            }
        }

        if (preparedStatement!=null) {
            if (preparedStatement!=null) {
                try {
                    preparedStatement.close();
                    preparedStatement=null;//GC recycling
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                    flag=false;
                }
            }

            if (connection!=null) {
                try {
                    connection.close();
                    connection=null;//GC recycling
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace ();
                    flag=false;
                }
            }


        }
        return flag;
    }
    
    
    // query operation
    public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params)
            throws SQLException{//The exception of the dao layer is to be thrown and received at the service layer
        
        preparedStatement=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1, params[i]);
        }
        resultSet=preparedStatement.executeQuery();
        return resultSet;
    }
    
    // update operation
    public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params)
            throws Exception{
        
        int updateRows=0;
        preparedStatement=connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1, params[i]);
        }
        updateRows=preparedStatement.executeUpdate();
        return updateRows;
    }
}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326676606&siteId=291194637
Recommended