我正在与Mysql后端spring引导应用程序工作,并试图使用springboots数据源Bean来获取连接对象,以便与以下stmts一起使用:
stmt =conn.createStatement()
stmt.executeQuery("show tables");
返回表列表。下面是连接类代码:
public class Test {
@Autowired
DataSource datasource;
public void test1(){
System.out.println("Inside Test Method");
try {
Connection conn = datasource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("show tables");
while (rs.next()) {
System.out.println(rs.getString("TableNames"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException e){
System.out.println("Null Pointer exception");
}
}
}
但是数据源对象抛出空值,因此它不返回任何连接对象。
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: ****
password: ****
initial-size: 1
max-idle: 2
max-active: 3
理想情况下,数据源对象应该读取这些属性并能够返回连接对象。不知道我的理解是否正确。
有谁能帮我解决这个问题吗?
我认为spring boot完全自动化了这个过程。不需要手动注入数据源&连接池机制也是自动化的。只是在yaml文件或src/main/resources下的属性文件中添加连接属性和池属性。它将为您注入数据源。