SSM2==springframework. Configure spring management data sources (. properties) and third-party jar packages (druid, mybatis) in pure XML, and compare them with those used alone before integration

         In“ SSM1==springframework. There are 4 ways to implement IOC with XML and 8 ways to implement DI. ”In, we know that the spring framework can give object A to IOC container management (creation) through IOC, and inject some attributes required by object A and object B into object A through DI. The above objects AB are all written by ourselves, so the jar packages provided by the third party are used in the real project. How can we hand them over to the IOC container for management?

         Now, for the three layers in the three-tier MVC architecture, we use servlet s as the controller layer to operate the model (pojo) through mybatis in the service. What can be created by the IOC container in the whole process? What dependency injection is required for the objects created by the IOC container?

        Firstly, the service object used in the controller layer can be created by the IOC container. Secondly, the sqlsessionfactory object of mybaitis required in the service layer can be created by the IOC container. Mybaitis needs to call the DRUID connection pool object, or it can be created by the IOC container, that is, the above three can be configured as beans. At the same time, you need to configure the dependency injection relationship in the three beans.

       =================================================================

1: Manage the DRUID connection pool object through spring.

         Let's take a look at how to use the DRUID connection pool without spring. The steps are:

        // java connects to mysql CRUD through the Druid connection pool
         // Import the jar package druid-1.1.12.jar,mysql-connector-java-5.1.48.jar
         // Define the configuration file druid.properties
         // Load the configuration file prop.load(new FileInputStream("src\druid.properties");
        // Get database connection pool object mode DataSource dataSource=   DruidDataSourceFactory.createDataSource(prop);
        // The second method to obtain the database connection pool object is druiddatasource; Then configure the properties through set
         // Get connection connection = dataSource.getConnection();

BrandTest code

package com.ldj.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.ldj.pojo.Brand;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

//java connects to mysql CRUD through the Druid connection pool
//Import the jar package druid-1.1.12.jar,mysql-connector-java-5.1.48.jar
//Define the configuration file druid.properties
//Load the configuration file prop.load(new FileInputStream("src\druid.properties");
//Get the database connection pool object in the first way: DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//The second method to obtain the database connection pool object is druiddatasource; Then configure the properties through set
//Get connection connection = dataSource.getConnection();
public class BrandTest {
    private Connection connection;

    @Before
    public void before() throws Exception {
        Properties prop = new Properties();
        System.out.println("The relative address is====" + System.getProperty("user.dir"));
        prop.load(new FileInputStream("src\\druid.properties"));

        //The first way to get a DataSource
//        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //The second way to get a DataSource
        DruidDataSource dataSource;

        String driverClassName = prop.getProperty("driverClassName");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        String initialSize = prop.getProperty("initialSize");
        String maxActive = prop.getProperty("maxActive");
        String maxWait = prop.getProperty("maxWait");

        dataSource = new DruidDataSource(); // Create Druid connection pool
        dataSource.setDriverClassName(driverClassName); // Set the database driver for the connection pool
        dataSource.setUrl(url); // Set the connection address of the database
        dataSource.setUsername(username); // User name of the database
        dataSource.setPassword(password); // Password for database
        dataSource.setInitialSize(Integer.parseInt(initialSize)); // Sets the initial size of the connection pool
        dataSource.setMaxActive(Integer.parseInt(maxActive)); // Set the maximum connection pool size
        dataSource.setMaxWait(Long.parseLong(maxWait));// Set connection pool retention time

        connection = dataSource.getConnection();
    }

    @Test
    public void selectAll() throws SQLException {
        System.out.println(System.getProperty("user.dir"));
        String sql = "select * from tb_brand";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet res = pstmt.executeQuery();
        ArrayList<Brand> brandList = new ArrayList<>();
        while (res.next()) {
            int id = res.getInt("id");
            String brandName = res.getString("brand_name");
            String companyName = res.getString("company_name");
            int ordered = res.getInt("ordered");
            String description = res.getString("description");
            int status = res.getInt("status");
            Brand brand = new Brand(id, brandName, companyName, ordered, description, status);
            brandList.add(brand);
        }
        System.out.println(brandList);
        pstmt.close();
        res.close();
    }



    @After
    public void after() throws SQLException {
        connection.close();
    }
}

          Then we hand over druid to IOC container management according to the above steps. There are two ways to use the Druid connection pool, so there are many ways to give it to spring. The first method is to hand over the instantiated object of DruidDataSourceFactory to IOC container management, but it is complex. We'd better leave the creation of the instantiated object of DruidDataSource to the IOC container for management, and inject the database account, password and other properties into the corresponding object bean through DI. In addition, we have to read the properties file to obtain the property value. The following are the implementation steps:

        1. Create a maven basic project and import the spring framework basic dependency package spring context

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

        2. Import DRUID, jdbc, junit dependent packages

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        3. Edit the spring configuration file and read the properties file of the saved account, password, etc. You need to use the context namespace, so change xmlns and xsi first

<?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="druid.properties" system-properties-mode="NEVER"/>
    <!--bean Label configuration bean
           id Attribute to bean give a name
           class Attribute is represented to bean Define type
           //The following configuration means that the objects of these two classes are handed over to the IOC container for creation
       -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="initialSize" value="${initialSize}"></property>
        <property name="maxActive" value="${maxActive}"></property>
        <property name="maxWait" value="${maxWait}"></property>
    </bean>
</beans>

        4. Configure the DruidDataSource as a bean managed by the IOC container, and specify the instantiation method as the default null parameter construction method to instantiate the bean. See "ssm1 = = spring framework. There are 4 ways to implement IOC with XML and 8 ways to implement DI."

        5. According to the source code of DruidDataSource, the implementation method of DI dependency injection is setter injection. According to the source code, the DruidDataSource class has only two constructors, and it can use many parameters. Users configure parameters according to their own needs, and Ali can't provide corresponding constructors one by one. So we can only use setter injection. "SSM1==springframework. There are 4 ways to implement IOC with XML and 8 ways to implement DI."

        6. Get a DruidDataSource object from the bean, get a Connection object from getConnection, and perform CRUD operation.

private Connection connection;

    @Before
    public void before() throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        DruidDataSource datasource = (DruidDataSource) ctx.getBean("dataSource");
        System.out.println(datasource);
        connection = datasource.getConnection();
        System.out.println(datasource);
    }

===============================================================

The project structure and code of spring configuration druid connection pool are as follows:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springDruid</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

    </dependencies>

</project>

 Brand

public class Brand {
    // id primary key
    private Integer id;
    // Brand name
    private String brandName;
    // Enterprise name
    private String companyName;
    // sort field
    private Integer ordered;
    // Description information
    private String description;
    // Status: 0: Disabled 1: enabled
    private Integer status;

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true
#When used with spring, the key must not use username, because the win system has a built-in variable, which will conflict with username.
# Or add system properties mode = "never" to the configuration file
username=root
password=1234
# ???????
initialSize=5
# ?????
maxActive=10
# ??????
maxWait=3000

 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:property-placeholder location="druid.properties" system-properties-mode="NEVER"/>
    <!--bean Label configuration bean
           id Attribute to bean give a name
           class Attribute is represented to bean Define type
           //The following configuration means that the objects of these two classes are handed over to the IOC container for creation
       -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="initialSize" value="${initialSize}"></property>
        <property name="maxActive" value="${maxActive}"></property>
        <property name="maxWait" value="${maxWait}"></property>
    </bean>
</beans>
BrandTest
import com.alibaba.druid.pool.DruidDataSource;
import ldj.pojo.Brand;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

//java connects to mysql CRUD through the Druid connection pool
//Import the jar package druid-1.1.12.jar,mysql-connector-java-5.1.48.jar
//Define the configuration file druid.properties
//Load the configuration file prop.load(new FileInputStream("src\druid.properties");
//Get the database connection pool object in the first way: DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//The second method to obtain the database connection pool object is druiddatasource; Then configure the properties through set
//Get connection connection = dataSource.getConnection();
public class BrandTest {
    private Connection connection;

    @Before
    public void before() throws Exception {
//Get container
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
//Remove the bean from the container
        DruidDataSource datasource = (DruidDataSource) ctx.getBean("dataSource");
        System.out.println(datasource);
        connection = datasource.getConnection();
        System.out.println(datasource);
    }

    @Test
    public void selectAll() throws SQLException {
        System.out.println(System.getProperty("user.dir"));
        String sql = "select * from tb_brand";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet res = pstmt.executeQuery();
        ArrayList<Brand> brandList = new ArrayList<>();
        while (res.next()) {
            int id = res.getInt("id");
            String brandName = res.getString("brand_name");
            String companyName = res.getString("company_name");
            int ordered = res.getInt("ordered");
            String description = res.getString("description");
            int status = res.getInt("status");
            Brand brand = new Brand(id, brandName, companyName, ordered, description, status);
            brandList.add(brand);
        }
        System.out.println(brandList);
        pstmt.close();
        res.close();
    }

}

       ====================================================================

         As mentioned above, we integrate druid connection pool into spring according to druid's traditional code. The same is true if you change a connection pool (such as DBCP, C3P0). First find the object that needs to inject parameters into the connection pool, then hand it over to the spring IOC container for management, and inject the necessary parameters through appropriate DI injection. For example, for C3P0 connection pool, you can see on the official website that this object is ComboPooledDataSource. Hand it over to the IOC container for management and inject the necessary parameters with setter. When using, get the container, take out the bean from the container and call the method.

There are two ways to obtain containers. The first is best. The second is that when the location of the project changes, the code also needs to be changed. It has a high degree of coupling and is not recommended.

          From the above, we can see that the IOC container we obtained is actually an interface called ApplicationContext. In fact, the beanfactory implemented by it can also be used. The timing of loading beans is different between the two. Beanfactory defaults to lazy init to delay loading beans into the container, As soon as the ApplicationContext program starts, the bean will be loaded into the container as soon as the ApplicationContext container is obtained, although it can be changed through settings. The understanding is as follows: at first, spring designers only designed the top-level interface beanfactory as the IOC container. Later, they found that the function was not enough, so they designed the ApplicationContext core interface as the IOC container. The latter also implemented the functions of other interfaces, such as closing the container and closing the container ctx.close(),   Register hook closer   ctx.registerShutDownHook().

 

There are three ways to obtain bean s:

 

 =========================================================================

2: Manage mybatis objects through spring.

         Let's take a look at how to use the DRUID connection pool without spring. The steps are as follows:

        1. Create a new maven project and import mybatis and jdbc dependency packages

        2. Write the mybatis global configuration file (alias, configure database connection environment information, including connection pool, and configure the path of mapper)

        3. Write mapper, mapper.xml

        4. Read the global configuration file, obtain the session factory SqlSessionFactory, obtain the session object SqlSession, obtain the mapper object through SqlSession, and call the CRUD method through the mapper object.

Refer to the official website of mybatis

Mybatis – MyBatis 3 | getting startedhttps://mybatis.org/mybatis-3/zh/getting-started.html         It can be seen that the important thing is to hand over SqlSessionFactory to the spring IOC container for management, which is simple. However, SqlSessionFactory needs a pile of parameters in the global configuration file, which also needs a pile of parameters. It is very complicated for us to write DI dependency injection one by one. Referring to the four instantiation methods of beans before, we can implement an interface f provided by spring Actorybean to instantiate objects. Mybatis provides a dependency package called mybatis spring. The class that implements FactoryBean in the dependency package is called SqlSessionFactoryBean.

         Therefore, after introducing the dependency package, we hand over the SqlSessionFactoryBean to the IOC container for management, and then inject a few simple parameters (the connection pool object must also be managed by spring and injected into the SqlSessionFactoryBean). When ctx.getBean, it will automatically call the getObjectType method in the SqlSessionFactoryBean to return the SqlSessionFactory object.

        In the above process, we get the SqlSessionFactory object, then openSession, getMapper gets the mapper, and then calls the method.

        According to the three-tier architecture, we can also hand over the service to the spring IOC container for management, and inject the mapper into the service object in the way of automatic assembly. The controller object is complex and will not be handed over to spring for management

        For the above objects managed by the IOC container, we can obtain them separately and then complete the subsequent processes for use. For example, we can obtain DataSource separately, SqlSessionFactory separately, mapper separately, or service directly.

        The steps of integrating mybatis with spring are as follows:

        1. Create a MAVEN project and import dependencies

        2. Write entity, mapper, mapper.xml and service

         3. Write database properties configuration file

        4. Writing spring configuration files

        5. Testing

Project structure:

Full code:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--spring IOC The container must have four dependencies, which can be imported separately or directly spring-context-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.12</version>
        </dependency>
        <!--It is necessary to connect to the data source, spring-jdbc take mysql Transaction to spring Administration-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <!--Database connection pool Druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!--mybatis 2 dependent packages, mybatis-spring Simplified configuration writing-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!--Test tool dependency package-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>


</project>

 Book

package com.ldj.entity;


public class Book {

    private String bookname;
    private Integer id;
    private int price;

    @Override
    public String toString() {
        return "Book{" +
                "bookname='" + bookname + '\'' +
                ", id=" + id +
                ", price=" + price +
                '}';
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

mapper

package com.ldj.mapper;

import com.ldj.entity.Book;

import java.util.List;

public interface BookMapper {
    List<Book> findAll();
}

 mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ldj.mapper.BookMapper">

    <select resultType="com.ldj.entity.Book" id="findAll">
        select * from book
    </select>

</mapper>

service

package com.ldj.service;

import com.ldj.mapper.BookMapper;
import com.ldj.entity.Book;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {

    private BookMapper bookMapper;

    public List<Book> findAll() {
        return bookMapper.findAll();
    }
//setter. Without annotations, there are two ways for a service to obtain a bookMapper:
// One is through automatic assembly setter injection,
// Second, we can also get the IOC container here, and then take it out of the IOC easily.
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
}

Database configuration

db.driveClass=com.mysql.cj.jdbc.Driver
db.username=root
db.password=1234
db.url=jdbc:mysql:///db1?useSSL=false&amp&useServerPrepStmts=true

spring configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--Import the properties file so that the data in it can be accessed with placeholders-->
    <context:property-placeholder location="classpath:db/db.properties"></context:property-placeholder>

    <!--Hand over the connection pool to spring IOC Container management: configuring data sources-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${db.driveClass}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>

    <!--take mybatis Factory to spring IOC Container management: sqlsessionfactory Configuration of,What you get is DefaultSqlSessionFactory object-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:mapper/BookMapper.xml"></property>
    </bean>

    <!--take mapper hand spring IOC Container management: mapper scanning,No configuration ID,When in use, it can be called directly with the initial lowercase,Convenient multiple mapper Administration-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <!--dao Package corresponding to interface-->
        <property name="basePackage" value="com.ldj.mapper"></property>
    </bean>

    <!--take service hand spring IOC Container management: autowire Property: turn on auto assembly because only one is used Mapper,Therefore, automatic assembly by type is used
    . Be sure to service Write the corresponding setter,Because in fact, the default is also used setter Injection, just reduced spring Configuration writing, no more writing property Configure properties,
    But it doesn't simplify the writing of the class.
    And we're up there mapper Yes, write free ID So it's best to use automatic assembly here.
    Of course, constructor injection in instantiation mode can also be used, because there is no ID,Can pass index and type To specify what to inject-->
    <bean id="bookService" class="com.ldj.service.BookService" autowire="byType"/>

</beans>

Write test class MyTest

import com.ldj.mapper.BookMapper;
import com.ldj.entity.Book;
import com.ldj.service.BookService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class MyTest {

    @Test
    public void test01() {
        //Get the DRUID connection pool object managed by the spring IOC container
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(ctx);
        Object dataSource = ctx.getBean("dataSource");
        System.out.println("Get to spring IOC Container managed DRUID Connection pool object===" + dataSource);
    }

    @Test
    public void te2() {
        //Get the SqlSessionFactoryBean managed by the spring IOC container, and a DefaultSqlSessionFactory object will be returned directly
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) ctx.getBean("sqlSessionFactory");
        System.out.println("Get to spring IOC Container managed SqlSessionFactory" + sqlSessionFactory);
        //There is no need to manually configure mysql jdbc transactions here, because spring TX in our dependency package spring JDBC has automatically handled transactions for us!!!
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        List<Book> all1 = mapper.findAll();
        System.out.println(all1);
    }

    @Test
    public void te3() {
        //Get the mapper managed by the spring IOC container
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookMapper bookMapper = (BookMapper) ctx.getBean("bookMapper");
        System.out.println(bookMapper);
        List<Book> all = bookMapper.findAll();
        System.out.println(all);
    }

    @Test
    public void te4() {
        //Get the service managed by the spring IOC container. Because automatic assembly by type is configured, bookMapper required by the service will be automatically generated at the same time
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) ctx.getBean("bookService");
        List<Book> all2 = bookService.findAll();
        System.out.println(all2);
    }
}

Tags: Spring xml jar

Posted on Sat, 06 Nov 2021 19:46:33 -0400 by jabba_29