关于spring:Spring全家桶单数据源的配置

1次阅读

共计 4542 个字符,预计需要花费 12 分钟才能阅读完成。

前言

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,咱们能够通过 http://localhost:8080/actuato… 看到 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 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,这里应用注解来实现(应用 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();}
}

运行 main 办法:

能够看到能够实现和 springboot 一样的成果

通过下面的两个例子,咱们能够看出 SpringBoot 帮咱们实现了如下性能:

  • 通过 DataSourceAutoConfiguration 配置 DataSource
  • 通过 DataSourceTransactionManagerAutoConfiguration 配置 DataSourceTransactionManager
  • 通过 JdbcTemplateAutoConfiguration 配置 JdbcTemplate
    当然下面是按需来配置的,如果咱们在代码中曾经配置了一个 DataSource,SpringBoot 不会再帮咱们配置一个 DataSource

在理论状况下,咱们可能须要在利用中配置多个数据源,下篇文章我将介绍多个数据源的配置形式。

正文完
 0