Pit Guide: three ways for Spring to configure data sources

  • πŸ‘ About the author: Hello, I'm cabbage ~ ~, a sophomore in school, and a new star creator in the Java field.
  • πŸ“ Personal homepage: Cabbage CSDN blog
  • πŸ“• Series column: This article is written in the Java design pattern column: Spring5 knowledge record
  • πŸ“§ If there are mistakes in the knowledge points of the article, please correct them! Learn and make progress with you πŸ‘€
  • πŸ”₯ If you feel the blogger's article is good, please πŸ‘ Three company support πŸ‘ Check out the blogger

1, Foreword

Today, I learned three ways to configure Druid data source with spring, and sorted out my study notes. I hope you like it!

2, Role of data sources

  • Data source (connection pool) is the key to improve program performance, such as
  • Instantiate the data source in advance and initialize some connection resources
  • Get from data source when using connection resources
  • Return the connected resources to the data source after use

Common data sources: DBCP, C3P0, BoneCP, Druid, etc. This paper mainly takes the Druid data source as an example to realize the development and application of Spring to the data source

3, How to develop data sources

Mode 1: manual input

First create a maven project and introduce dependencies. For convenience, I also imported Junit dependencies. In addition, there are mysql driver dependencies, Druid data source dependencies and spring dependencies

 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.14</version>
        </dependency>
    </dependencies>

Write a test class directly and start testing

    @Test
    public void test1() throws SQLException {
    	//Create data source object
        DruidDataSource dataSource = new DruidDataSource();
        //Set the basic connection data of the data source
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("0315");
        //Get connection resources using data sources
        Connection connection = dataSource.getConnection();
        //Print information about connected resources
        System.out.println(connection);
        //Close connection resource
        connection.close();
    }

Analysis: setDriverClassName() fills in the package path of the connection Driver class Driver, setUrl() sets the address of the database to be connected, setUsername() own database user name, and setPassword() database password

Operation results:

Method 2: Properties configuration file

Under resources, create a database called JDBC Properties file to fill in the basic connection data of the data source

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=0315

Write a test class and start testing

	@Test
    public void test2() throws SQLException {
    	//ResourceBundle is used to read files of type properties
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        //Set the basic connection data of the data source
        String driver = bundle.getString("jdbc.driver");
        String url = bundle.getString("jdbc.url");
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

This method is much better than method 1. If the database we use changes, we only need to modify it in the Properties file, so we don't need to modify it from the code, which improves the efficiency of development

Method 3: configure data source in Spring

Continue to use the previous JDBC Properties file, we can hand over the creation right of the data source to the spring container and write an application context XML spring configuration file and put the data source into the spring container

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0315"></property>
    </bean>
</beans>

Through this spring configuration file, we can obtain the data source, and then write a code to test

  @Test
    public void test3() throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class);
        DruidPooledConnection connection = dataSource.getConnection();
        //Print connection information
        System.out.println(connection);
        connection.close();
    }

Operation results:

I don't know if my friends feel any discomfort when they see that the attribute value of value is so long. Anyway, I do. So is there a way to make the configuration clearer? The answer is: Yes! So what should I do?

The first thing to do is to put JDBC The object of the properties configuration file is put into the spring container, which facilitates future calls. The specific code is as follows:

<?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:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

Analysis: first, introduce the namespace shown in the following figure into the header file, and finally get the attribute value of value to JDBC by ${key} The value value of properties. The running result is the same as above

4, Summary

What we need to master most is the last method. We must learn this configuration method!

Keywords: Java Spring intellij-idea

Added by gortron on Wed, 19 Jan 2022 11:37:02 +0200