Spring Boot自定义Druid数据源

添加相关依赖

<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>
    </dependency>
</dependencies>

Druid数据源配置

配置application.properties,首先是基本的链接属性,然后是Druid的相关属性配置

spring:
  datasource:
    #type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?useSSL=false&requireSSL=false
    username: root
    password: root

注入自定义dataSource

使用@Bean("dataSource")覆盖默认的dataSource数据源,由于没有配置spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcecom.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;
    }
}

测试

实体

@Setter
@Getter
@Entity
@Table(name = "customer")
public class Customer implements Serializable {

    @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@appblog.cn");
        customer.setMobile("10086");
        customer.setNikeName("Joe.Ye");
        customer.setPhone("010-10086");
        customerService.create(customer);
    }

    @Test
    public void testRollback(){
        Customer customer = new Customer();
        customer.setAddress("浙江杭州");
        customer.setEmail("xxx@appblog.cn");
        customer.setMobile("10086");
        customer.setNikeName("rollbackUser");
        customer.setPhone("010-10086");
        customerService.create(customer);
    }

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

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/spring-boot-custom-druid-data-source/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Boot自定义Druid数据源
添加相关依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>s……
<<上一篇
下一篇>>
文章目录
关闭
目 录