使用JavaFX+JDK20开发时遇java.sql模块'requires transitive'缺失警告
解决JavaFX项目中java.sql模块类型访问警告问题
问题背景
用JavaFX结合JDK20、Eclipse开发项目时,数据库操作环节出现警告:java.sql模块的Connection、ResultSet、PreparedStatement等类型因缺少requires transitive声明,可能无法被客户端访问。
警告详情
Description Resource Path Location Type The type Connection from module java.sql may not be accessible to clients due to missing 'requires transitive' dbConnect.java /myProject/src/mypackage line 25 Java Problem
相关代码
dbConnect.java
package mypackage; import java.io.IOException; import java.sql.*; // 引用java.sql包下的类 import java.util.Properties; public class dbConnect { // 初始化数据库常量 static final String databaseDriver = "oracle.jdbc.driver.OracleDriver"; static final String databaseURL = "jdbc:oracle:thin:@localhost:1521:xe"; static final String username = "system"; static final String pass = "oracle"; private Connection connection; private Properties properties; private Statement statement; /** * 连接数据库 * * @return Connection */ public Connection connect() { if (connection == null) { try { Class.forName(databaseDriver); connection = (Connection) DriverManager.getConnection (databaseURL, getProperties()); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } return connection; } // 省略其他代码
module-info.java
module myProject{ requires transitive javafx.graphics; requires javafx.controls; requires javafx.fxml; requires javafx.base; requires javafx.web; requires java.sql; opens mypackage to javafx.fxml; exports mypackage; }
解决方案
修改module-info.java中的requires java.sql;为requires transitive java.sql;,修改后的模块声明如下:
module myProject{ requires transitive javafx.graphics; requires javafx.controls; requires javafx.fxml; requires javafx.base; requires javafx.web; requires transitive java.sql; opens mypackage to javafx.fxml; exports mypackage; }
原因说明
你的模块通过exports mypackage;对外暴露了mypackage包,而dbConnect类的connect()方法返回了java.sql.Connection类型——这属于java.sql模块的公开类型。当其他模块依赖你的myProject模块并调用该方法时,如果仅用requires java.sql;,客户端模块需要自己显式声明requires java.sql;才能访问这些类型;而requires transitive java.sql;会将java.sql模块的依赖传递给所有依赖myProject的模块,确保客户端能正常访问Connection等类型,同时消除警告。
内容的提问来源于stack exchange,提问作者F.M
相关产品推荐
相关产品推荐

