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