springboot学习笔记二-配置c3p0数据源连接Mysql数据库

1.首先引入c3p0和jdbc的pom依赖

 
     mysql
     mysql-connector-java
 
 
     c3p0
     c3p0
     0.9.1.2
  

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);

        return dataSource;
    }
}

4注意事项:配置类要加SpringBootConfiguration注解,value注解可以取到properties配置文件中的数据,方法上要加Bean注解,以便springboot可以扫描到此配置。当然你也可以指定配置文件路径,通过@PropertySource({"classpath:allocation/alidayu.properties"})

你可能感兴趣的:(springboot)