SpringBoot 官方文档示例(89):使用DataSourceBuilder构建数据源

时间:2023-02-18 12:57:15


一、在application.properties中配置数据源信息

app.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx/test
app.datasource.jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx/test
app.datasource.username=root
app.datasource.password=MyPass1234
app.datasource.pool-size=30

二、在配置类中手动配置DataSource

@Bean("myDataSource")
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}

三、在controller中注入DataSource

package cn.edu.tju.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.SQLException;

@RestController
public class DataSourceController {
@Autowired
@Qualifier("myDataSource")
private DataSource dataSource;

@RequestMapping("/data")
public String hi() throws SQLException {
System.out.println("#####################################################");
System.out.println(dataSource.getClass().getName());
dataSource.getConnection().createStatement().execute("XXXXXXXXXXXXXXXXXXXXXXXXXXX");
return "ok";
}
}

#######################################################
或者

@Bean
@Primary
@ConfigurationProperties("app.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource.configuration")
public HikariDataSource dataSource(DataSourceProperties properties) {
return
properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
app.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx/test
#app.datasource.jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx/test
app.datasource.username=root
app.datasource.password=MyPass1234
app.datasource.pool-size=30