SpringBoot配置Druid

Scroll Down

1. 导入Druid依赖

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>

2. 新建一个配置类

@Configuration
public class MyDataSourceConfig {
    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
  • @Configuration:用于定义配置类
  • @ConfigurationProperties("spring.datasource"):通过指定的前缀,绑定配置文件中的配置
  • @Bean:把这个对象交给Spring管理

3. yml文件内容

spring:
  datasource:
    url: jdbc:mysql://xxx:3306/jdbc?serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

4. 验证是否为Druid

@Slf4j
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() {
        log.info("数据源类型{}",dataSource.getClass());
    }
}
  • 数据源类型class com.alibaba.druid.pool.DruidDataSource