其他分享
首页 > 其他分享> > 2021-09-19当使用ClassLoader.getSystemClassLoader().getResourceAsStream(“jdbc.properties“);时报空指针异常

2021-09-19当使用ClassLoader.getSystemClassLoader().getResourceAsStream(“jdbc.properties“);时报空指针异常

作者:互联网

当使用ClassLoader.getSystemClassLoader().getResourceAsStream(“jdbc.properties“);时报空指针异常
浏览器报错如下

首先是自定义的ConnectionUtils的一些方法,代码如下

public class ConnectionUtils {
    private static Connection connection = null;
    private static DataSource dataSource = null;
    
    public static Connection getConnection() {
        try {
            connection = dataSource.getConnection();
            System.out.println("data="+dataSource);
            System.out.println("con="+connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}


其中关于静待变量和静态初始化代码块



    static{
        try {
            Properties properties = new Properties();
            System.out.println(properties);
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这个方法在不涉及 Tomcat 服务器时,本地测试没有问题,但是一涉及到 Tomcat 服务器时,即往数据库写入数据,那么肯定会执行代码块片段,下面是 Tomcat 服务器端报错信息

java.lang.NullPointerException: inStream parameter is null
	at java.base/java.util.Objects.requireNonNull(Objects.java:246)
	at java.base/java.util.Properties.load(Properties.java:407)
	at com.example.utils.ConnectionUtils.getConnection(ConnectionUtils.java:30)
	at com.example.dao.BaseDao.queryForOne(BaseDao.java:44)
	at com.example.dao.impl.UserDaoImpl.queryUserByUsername(UserDaoImpl.java:14)
	at com.example.service.impl.T_UserServiceImpl.existsUsername(T_UserServiceImpl.java:22)
	at com.example.servlet.RegistServlet.doPost(RegistServlet.java:24)

第30行空指针异常了


经过测试使用自定义类的加载器并不会报这个错误,代码如下

 static {
        try {
            Properties pro = new Properties();
            InputStream in = ConnectionUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
//            InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
            pro.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

标签:getSystemClassLoader,getResourceAsStream,java,19,Properties,connection,static,da
来源: https://blog.csdn.net/HE_BINCNDS/article/details/120378906