A big pit when loading the configuration file

When using druid as a project today, the configuration file has not been loaded:

public class JDBCUtils {
    private static DataSource ds;
    //静态代码块加载好配置文件,并给ds赋值
    static {
        try {
            Properties pro = new Properties();
            InputStream res = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
//            FileInputStream res = new FileInputStream("druid.properties");
            pro.load(res);
            //返回值赋值给ds
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接池连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 获取DataSource接口
     * @return
     */
    public static DataSource getDataSource(){
        return ds;
    }

 
}

 

 

report an error

inStream parameter is null at java.base/java.util.Objects.requireNonNull(Objects.java:246) at java.base/java.util.Properties.load(Properties.java:403)

That is to say, the input stream is empty, and loading the configuration file failed!

 

The reason was later found out:

Key statement:

InputStream res = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");

An error occurred

At first I thought that druid.properties can be placed anywhere, because we need to load it manually.

The result may be because I didn't put it under src, and then the scope of classload is limited, so it can't be loaded all the time

(First time to understand that the scope of class loader is limited)

 

so:

That's no problem

or use:

FileInputStream res = new FileInputStream("druid.properties");

The scope is larger than classload, so you don't need to put the configuration file under src

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326388532&siteId=291194637