Spring [Annotations to achieve IOC (@Configuration, @ComponentScan, @PropertySource)] (4) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Annotation implements IOC_@Configuration 

Annotation implements IOC_@ComponentScan

 Annotation implements IOC_@PropertySource

Annotation implements IOC_@Bean

Annotation implements IOC_@Import 

Spring integrates MyBatis_ build environment

Spring integrates MyBatis_ writing configuration files


 

Annotation implements IOC_@Configuration 

 At this point, the annotation-based IOC configuration has been completed, but we still cannot do without Spring's xml configuration file. Next, we break away from bean.xml and use pure annotations to implement IOC.

In real development, we generally still keep the xml configuration file, and it is more convenient to use the configuration file in many cases.

 Pure annotation implementation of IOC requires a Java class instead of an xml file. @Configuration needs to be added above this Java class, indicating that this class is a configuration class, which is used to replace the configuration file.

@Configuration
public class SpringConfig {  
}

Annotation implements IOC_@ComponentScan

Role: Specify the package that spring scans when initializing the container.

Location: above the configuration class

@Configuration
@ComponentScan("com.tong")
    public class SpringConfig { }

 Annotation implements IOC_@PropertySource

 Function: replace the <context:property-placeholder> in the configuration file to scan the configuration file

Location: above the configuration class

Note: The keyword classpath should be added before the location of the configuration file

@Configuration
@PropertySource("classpath:db.properties")
public class JdbcConfig {
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
}

Annotation implements IOC_@Bean

Function : Put the return value object of the method into the Spring container. If you want to put objects of third-party classes into containers, you can use @Bean

Location : above the method of the configuration class.

Attribute : name: set the id for the bean object

Note : If the method modified by @Bean has parameters, spring will look for available objects from the container according to the parameter type.

Example : If we want to put the jdbc connection object into the Spring container, we cannot modify the Connection source code to add @Component, then we need to use @Bean to put the object into the Spring container

 1. Add driver dependencies

    

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.27</version>
</dependency>

2. Put the Connection object into the Spring container

@Bean(name = "connection")
public Connection getConnection(){
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
        returnDriverManager.getConnection("jdbc:mysql:///mysql", "root", "root");
   } catch (Exception exception) {
        return null;
   }
}

3. Test

@Test
public void t5(){
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    Connection connection = (Connection)ac.getBean("connection");
    System.out.println(connection);
}

Annotation implements IOC_@Import 

 Function: If there are too many configurations, there will be multiple configuration classes. This annotation can import other configuration classes for the main configuration class

 Location: above the main configuration class

// Jdbc配置类
@Configuration
public class JdbcConfig {
    @Bean(name = "connection")
    public Connection getConnection(){
        try {
          Class.forName("com.mysql.cj.jdbc.Driver");
          return DriverManager.getConnection("jdbc:mysql:///mysql", "root", "root");
       } catch (Exception exception) {
            return null;
       }
   }
}
// 主配置类
@Configuration
@ComponentScan("com.tong")
@Import(JdbcConfig.class)
public class SpringConfig { }

Spring integrates MyBatis_ build environment

 We know that when using MyBatis, we need to write a lot of code to create objects such as SqlSessionFactoryBuilder, SqlSessionFactory, SqlSession, etc., and the role of Spring is to help us create and manage objects, so we can use Spring to integrate MyBatis and simplify MyBatis development.

Create a maven project and introduce dependencies.

<dependencies>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <!-- mysql驱动包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.13</version>
    </dependency>

    <!-- MyBatis与Spring的整合包,该包可以让Spring创建MyBatis的对象 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
</dependencies>

Spring integrates MyBatis_ writing configuration files

 1. Write the database configuration file db.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///student
jdbc.username = root
jdbc.password01 = root

2. Create the MyBatis configuration file SqlMapConfig.xml. The data source and scanning interface are all managed by Spring and do not need to be set in the MyBatis configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

3. Create the Spring configuration file applicationContext.xml

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 包扫描 -->
    <context:component-scan base-package="com.tong"></context:component-scan>
    <!-- 读取配置文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!-- 创建druid数据源对象 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- Spring创建封装过的SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- Spring创建封装过的SqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131744249