您的位置:首页 > 编程语言 > Java开发

spring boot入门(二) 配置c3p0数据源连接Mysql数据库。最完整、简单易懂、详细的spring boot教程。

2018-07-04 17:14 1351 查看
版权声明:版权所有 © 侵权必究 https://blog.csdn.net/m0_38075425/article/details/80915143

本文紧接spring boot入门(一)

1.首先引入c3p0和jdbc的pom依赖,代码如下:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
2.resources文件夹下的application.properties(spring boot 的默认配置文件),代码如下:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=xxx
3.建立spring boot配置类,代码如下:
@SpringBootConfiguration
public class DataSourceConfiguration {
@Value("${spring.datasource.driver-class-name}")
private String driver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setAutoCommitOnClose(false);
dataSource.setInitialPoolSize(10);
dataSource.setMinPoolSize(10);
dataSource.setMaxPoolSize(100);
System.out.print("========================================="+dataSource+"===========================================");
return dataSource;
}
}
4.运行测试:


5.注意事项:配置类要加SpringBootConfiguration注解,value注解可以取到properties配置文件中的数据,方法上要加Bean注解,以便springboot可以扫描到此配置。



阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐