[Properties]写配置文件前,必须初始化Properties(引用变量没执行有效对象,调用方法会报空指针错误)

复制代码
package BaseDAO;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

//创建连接和释放连接的工具类
public class JDBCUtil {
    private static DataSource ds;
    private static Properties properties;//只是在堆里创建了个存放properties地址的空间
    static {
        try {
            properties = new Properties(); // 👈 必须先初始化!引用变量未指向有效对象,调用方法会报空指针
            properties.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("Failed to initialize JDBCUtil: " + e.getMessage());
        }
    }


    public static Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Connection connection){
        if(connection != null){
            try {
                connection.close();//归还线程池
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

如果不初始化

相关推荐
哈里谢顿20 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee2 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay2 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤2 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽2 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188962 天前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api