spring-boot入门(五)自定义数据源:druid

本文介绍了如何在Spring Boot中使用Druid数据源,包括添加相关依赖、配置application.properties文件以及如何覆盖默认的Tomcat数据源。通过示例代码展示了从实体、Service到测试的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring-boot入门(五)自定义数据源:druid

上一章讲了如何使用默认的tomcat数据源及用hibernate与数据库交互,这篇我们以阿里的druid数据源为例子,来说下如何使用自定义的数据源。
如何spring boot在启动的时候检测到类路径下存在DataSource.class, EmbeddedDatabaseType.class这两个类(也就是引入了spring-boot-starter-jdbc或者jdbc相关jar包)就会自动帮我们配置数据源。详细实现请查看org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration源码,当然在DataSourceAutoConfiguration里面就是使用的tomcat数据源。

1. 添加相关依赖

  • druid
  • mysql驱动
  • jdbc相关
  • spring boot相关
    pom文件如下:
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
    </dependencies>

2.druid数据源配置

  • 配置application.properties 首先是基本的链接属性,然后是druid的相关属性配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db1?useSSL=false&requireSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root

druid:
  filters: stat
  maxActive: 20
  initialSize: 1
  maxWait: 30000
  minIdle: 10
  maxIdle: 15
  timeBetweenEvictionRunsMillis: 60000
  minEvictableIdleTimeMillis: 300000
  validationQuery: SELECT 1
  testWhileIdle: true
  testOnBorrow: false
  testOnReturn: false
  maxOpenPreparedStatements: 20
  removeAbandoned: true
  removeAbandonedTimeout: 1800
  logAbandoned: true
  • 注入自定义dataSource
    使用@Bean(“dataSource”)覆盖默认的tomcat数据源,由于com.alibaba.druid.pool.DruidDataSource#configFromPropety方法没有将url,username,password,driver-class-name注入进去,所以需要自已手动设置。
@Configuration
public class CustomConfiguration {

    @Value("${spring.datasource.url}")
    String url;

    @Value("${spring.datasource.username}")
    String username;

    @Value("${spring.datasource.password}")
    String password;

    @Value("${spring.datasource.driver-class-name}")
    String driverClassName;

    @Bean("dataSource")
    public DataSource druidDataSource(StandardEnvironment env) {
        Properties properties = new Properties();
        DruidDataSource druidDataSource = new DruidDataSource();
        PropertySource<?> appProperties = env.getPropertySources().get("applicationConfig: [classpath:/application.yml]");
        Map<String,Object>  source = (Map<String, Object>) appProperties.getSource();
        properties.putAll(source);
        druidDataSource.configFromPropety(properties);
        druidDataSource.setUrl(url);
        druidDataSource.setPassword(username);
        druidDataSource.setUsername(password);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }
}

3.一些测试用的代码

  • 实体
@Setter
@Getter
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = -7896459795783095454L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "nike_name")
    private String nikeName;

    @Column
    private String email;

    @Column
    private String mobile;

    @Column
    private String phone;

    @Column
    private String address;
}
  • service层
@Service("customerService")
@Transactional(rollbackFor = Exception.class)
public class CustomerServiceImpl implements CustomerService {

    private static final String INSERT_CUSTOMER = "INSERT INTO customer (nike_name,email,mobile,phone,address) VALUES (?,?,?,?,?);";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void create(Customer customer) {
        jdbcTemplate.update(INSERT_CUSTOMER, customer.getNikeName(),
                customer.getEmail(), customer.getMobile(),
                customer.getPhone(), customer.getAddress());
        if("rollbackUser".equals(customer.getNikeName())){
            throw new RuntimeException("test rollback on runtimeException.");
        }
    }
}
  • 测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestCustomerService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testCreateCustomer(){
        Customer customer = new Customer();
        customer.setAddress("四川成都");
        customer.setEmail("xxx@qq.com");
        customer.setMobile("15708111111");
        customer.setNikeName("JasonLin");
        customer.setPhone("028-125468");
        customerService.create(customer);
    }

    @Test
    public void testRollback(){
        Customer customer = new Customer();
        customer.setAddress("四川成都");
        customer.setEmail("xxx@qq.com");
        customer.setMobile("15708111111");
        customer.setNikeName("rollbackUser");
        customer.setPhone("028-125468");
        customerService.create(customer);
    }

    @Test
    public void testSearchCustomer() {
        String sql = "SELECT id FROM customer WHERE nike_name = 'JasonLin'";
        Assert.notEmpty(jdbcTemplate.queryForList(sql, Long.class));
    }
}

详细的代码在:https://github.com/Json-Lin/spring-boot-practice/tree/master/spring-boo-practice-custom-datasource

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值