前言
spring數(shù)據(jù)源的配置網(wǎng)絡(luò)上有很多例子禾酱,這里我也來(lái)介紹一下單數(shù)據(jù)源配置的例子,基于SpringBoot的方式和原生的Spring的方式。
一已骇、生成項(xiàng)目骨架(SpringBoot),運(yùn)行一個(gè)簡(jiǎn)單的程序
訪問:https://start.spring.io/ 票编,選擇必要的依賴
下面我們先看下Application類的代碼:
@SpringBootApplication
@Slf4j
public class SpringDatasourceApplication implements CommandLineRunner {
@Autowired
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringDatasourceApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
showConnection();
showData();
}
private void showConnection() throws SQLException {
log.info("數(shù)據(jù)源:"+dataSource.toString());
Connection conn = dataSource.getConnection();
log.info("連接:"+conn.toString());
conn.close();
}
private void showData() {
jdbcTemplate.queryForList("SELECT * FROM user")
.forEach(row -> log.info("記錄:"+row.toString()));
}
}
application.properties文件的配置項(xiàng)褪储,我們可以看到我們使用的h2數(shù)據(jù)庫(kù)
management.endpoints.web.exposure.include=*
spring.output.ansi.enabled=ALWAYS
spring.datasource.url=jdbc:h2:mem:demodb
spring.datasource.username=sa
spring.datasource.password=
在資源文件目錄,寫入兩個(gè)文件慧域,一個(gè)是data.sql鲤竹、一個(gè)是schema.sql
schema.sql內(nèi)容是:
CREATE TABLE user (ID INT IDENTITY, name VARCHAR(64),age INT);
data.sql內(nèi)容是:
INSERT INTO user (ID,name,age) VALUES (1, '張三',18);
INSERT INTO user (ID, name,age) VALUES (2, '李四',19);
運(yùn)行代碼,結(jié)果如下:
其實(shí)我們并沒有去對(duì)DataSource進(jìn)行bean配置昔榴,只是指定了數(shù)據(jù)庫(kù)的類型辛藻,加載了建表語(yǔ)句和初始化數(shù)據(jù)語(yǔ)句,可以看到連接池是Hikari互订,這也是springboot默認(rèn)的連接池吱肌。
由于是使用的內(nèi)置數(shù)據(jù)庫(kù),我們可以在代碼中
這也是因?yàn)閟pringboot給我們自動(dòng)裝配了我們所需要的信息仰禽,由于我們引入了actuator氮墨,我們可以通過http://localhost:8080/actuator/beans 看到springboot幫我們裝載了很多的bean,有些可能是我們根本用不到的吐葵。下面我們講一下原生Spring方式怎么實(shí)現(xiàn)配置數(shù)據(jù)源规揪。
二、選擇原生Spring方式配置數(shù)據(jù)源
pom文件配置內(nèi)容:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope>
</dependency>
```
**創(chuàng)建applicationContext.xml文件温峭,內(nèi)容如下:**
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.xxx.xxxx" />
<!--
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:testdb"/>
<property name="username" value="SA"/>
<property name="password" value=""/>
</bean>
-->
</beans>
** 自定義DataSource粒褒,這里使用注解來(lái)實(shí)現(xiàn)(使用dbcp連接池) **
@Configuration
@EnableTransactionManagement
public class DataSourceDemo {
@Autowired
private DataSource dataSource;
public static void main(String[] args) throws SQLException {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext*.xml");
showBeans(applicationContext);
dataSourceDemo(applicationContext);
}
@Bean(destroyMethod = "close")
public DataSource dataSource() throws Exception {
Properties properties = new Properties();
properties.setProperty("driverClassName", "org.h2.Driver");
properties.setProperty("url", "jdbc:h2:mem:testdb");
properties.setProperty("username", "sa");
return BasicDataSourceFactory.createDataSource(properties);
}
@Bean
public PlatformTransactionManager transactionManager() throws Exception {
return new DataSourceTransactionManager(dataSource());
}
private static void showBeans(ApplicationContext applicationContext) {
System.out.println(Arrays.toString(applicationContext.getBeanDefinitionNames()));
}
private static void dataSourceDemo(ApplicationContext applicationContext) throws SQLException {
DataSourceDemo demo = applicationContext.getBean("dataSourceDemo", DataSourceDemo.class);
demo.showDataSource();
}
public void showDataSource() throws SQLException {
System.out.println(dataSource.toString());
Connection conn = dataSource.getConnection();
System.out.println(conn.toString());
conn.close();
}
}
運(yùn)行main方法:
可以看到可以實(shí)現(xiàn)和springboot一樣的效果
通過上面的兩個(gè)例子,我們可以看出SpringBoot幫我們實(shí)現(xiàn)了如下功能:
- 通過DataSourceAutoConfiguration 配置 DataSource
- 通過DataSourceTransactionManagerAutoConfiguration 配置 DataSourceTransactionManager
- 通過JdbcTemplateAutoConfiguration 配置 JdbcTemplate
當(dāng)然上面是按需來(lái)配置的诚镰,如果我們?cè)诖a中已經(jīng)配置了一個(gè)DataSource奕坟,SpringBoot不會(huì)再幫我們配置一個(gè)DataSource
在實(shí)際情況下,我們可能需要在應(yīng)用中配置多個(gè)數(shù)據(jù)源清笨,下篇文章我將介紹多個(gè)數(shù)據(jù)源的配置方式月杉。