当前位置:   article > 正文

Java单例模式读取MySql配置文件_单例模式读取配置文件

单例模式读取配置文件

单例的数据库连接类:

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

public class Singleton {
    // 创建单例对象
    private static Singleton singleton;
    // 创建数据库获取连接的对象
    private static Connection singletonConnection = null;

    // 将构造方法私有化,防止外部new
    public Singleton() throws Exception {
        singletonConnection = Singleton.getConnection();

    }

    private static Connection getConnection() throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src\\main\\resources\\jdbc.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection singletonConnection = dataSource.getConnection();
        return singletonConnection;
    }

    //  对外提供实例化的方法
    public static Connection getInstance() throws Exception {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singletonConnection;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

测试类:

package com.gy.config;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class test {
    public static void main(String[] args) throws Exception {
        Connection instance = Singleton.getInstance();
        Connection instance1 = Singleton.getInstance();
        Connection instance2 = Singleton.getInstance();
        System.out.println(instance);
        System.out.println(instance1);
        System.out.println(instance2);
        System.out.println("============================");
        Statement statement = instance.createStatement();
        String sql="select * from user";
        ResultSet resultSet = statement.executeQuery(sql);
        List<User> users=new ArrayList<>();
        while (resultSet.next()){
            String name = resultSet.getString(1);
            String password = resultSet.getString(2);
            int id = resultSet.getInt(3);
            User user = new User(name, password, id);
            users.add(user);
        }
        System.out.println(users);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

运行结果:(成功返回单例对象
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/157727
推荐阅读
相关标签
  

闽ICP备14008679号