spring数据源的配置网络上有很多例子,这里我也来介绍一下单数据源配置的例子,基于SpringBoot的方式和原生的Spring的方式。
一、生成项目骨架(SpringBoot),运行一个简单的程序访问: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("数据源:"+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文件的配置项,我们可以看到我们使用的h2数据库
management.endpoints.web.exposure.include=* spring.output.ansi.enabled=ALWAYS spring.datasource.url=jdbc:h2:mem:demodb spring.datasource.username=sa spring.datasource.password=在资源文件目录,写入两个文件,一个是data.sql、一个是schema.sql
schema.sql内容是:
CREATE TABLE user (ID INT IDENTITY, name VARCHAR(64),age INT);data.sql内容是:
INSERT INTO user (ID,name,age) VALUES (1, '张三',18); INSERT INTO user (ID, name,age) VALUES (2, '李四',19);运行代码,结果如下:
其实我们并没有去对DataSource进行bean配置,只是指定了数据库的类型,加载了建表语句和初始化数据语句,可以看到连接池是Hikari,这也是springboot默认的连接池。
由于是使用的内置数据库,我们可以在代码中
这也是因为springboot给我们自动装配了我们所需要的信息,由于我们引入了actuator,我们可以通过:8080/actuator/beans 看到springboot帮我们装载了很多的bean,有些可能是我们根本用不到的。下面我们讲一下原生Spring方式怎么实现配置数据源。
二、选择原生Spring方式配置数据源pom文件配置内容:
<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> ``` **创建applicationContext.xml文件,内容如下:** ```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 "> <context:component-scan base-package="com.xxx.xxxx" /> <!-- <bean destroy-method="close"> <property value="org.h2.Driver"/> <property value="jdbc:h2:mem:testdb"/> <property value="SA"/> <property value=""/> </bean> --> </beans>** 自定义DataSource,这里使用注解来实现(使用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(); } }