Spring+SpringMVC+MyBatis integration

Table of contents

  • 1.SSM introduction
    • 1.1 What is SSM?
  • 1.2 SSM framework
    • 1.2.1 Spring
  • 1.2.2 SpringMVC
  • 1.2.3 MyBatis
  • 2.SSM framework integration
    • 2.1 Create database and table
  • 2.2 Create project
  • 2.3 pom.xml
  • 2.4 log4j.properties
  • 2.5 db.properties
  • 2.6 applicationContext-dao.xml
  • 2.7.applicationContext-tx.xml
  • 2.8 applicationContext-service.xml
  • 2.9 springmvc.xml
  • 2.10 web.xml
  • 2.11 pojo
  • 2.12 mapper
  • 2.13 service
  • 2.14 controller
  • 2.15 jsp
  • 2.16 Testing
  • 2.17 Project directory structure
    1. Problems to be reformed
    • 3.1 jdbc configuration
  • 3.2 mybatis configuration
  • 3.3 transactional configuration
  • 3.4 service configuration
  • 3.5 springmvc configuration
  • 3.6 servlet configuration
    1. Relevant explanations
    • 4.1 Correspondence between related comments and xml
  • 4.2 @Configuration
  • 4.3 @ComponentScan
  • 4.4 @Bean
  • 4.5 @PropertySource
  • 4.6 @Import
  • 5.Spring’s pure annotation configuration
    • 5.1 JdbcConfig
  • 5.2 MybatisConfig
  • 5.3 TxConfig
  • 5.4 SpringConfig
  • 5.5 SpringMvcConfig
  • 5.6 WebConfig
  • 5.7 Delete xml configuration file
  • 5.8 Modify web.xml
  • 5.9 Testing

1.SSM introduction

1.1 What is SSM?

SSM's full name is Spring+SpringMVC+MyBatis. It is an integration of spring, spring MVC, and mybatis frameworks. It is a standard MVC model and is currently a mainstream Java EE enterprise-level framework. It is suitable for building various large-scale enterprise-level application systems.

  • Use Spring to manage business objects;

  • Use SpringMVC to be responsible for request forwarding and view management;

  • Use MyBatis as the persistence engine for data objects.

The standard SSM framework has four layers, namely dao(mapper) layer, service layer, controller layer and View layer. Use spring to implement business object management, use spring MVC to be responsible for request forwarding and view management, and mybatis as the persistence engine for data objects.

1.2 SSM framework

1.2.1 Spring

Spring is an open source inversion of control (IoC) and aspect-oriented (AOP) container framework used to simplify enterprise development.

  • IOC (Inversion of Control)

It is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. The most common method is called Dependency Injection (DI). Through control inversion, when an object is created, An external entity that controls all objects in the system passes the reference of the object it depends on to it. It can also be said that dependencies are injected into the object.

  • AOP (Aspect Oriented Programming)

AOP reduces the coupling between various parts of business logic, improves program reusability, and improves development efficiency.

Detailed reference: Spring IoC detailed explanation, Spring AOP detailed explanation

1.2.2 SpringMVC

Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, making them easier to customize.

Advantages of SpringMVC:

  1. springMVC is a lightweight web framework that uses MVC design ideas to decouple the web layer, making our development simpler.

  2. Seamlessly connect with Spring.

  3. Flexible data validation, formatting, and data binding mechanisms.

Detailed reference: Spring MVC detailed explanation, Spring MVC interceptor, file upload and global exception handling

1.2.3 MyBatis

MyBatis is an open source persistence framework that configures SQL mapping through XML or annotations to map Java objects to tables in a relational database. MyBatis can map data query results into Java objects, and can also insert, update, and delete Java objects into the database.

The core components of MyBatis include:

  1. SqlSessionFactory: Create a SqlSession factory class to generate SqlSession objects.

  2. SqlSession: The session that MyBatis interacts with the database. You can use SqlSession to perform database operations, such as query, update, delete, insert, etc.

  3. Mapper: Mapper is a Java interface used to define database operation methods. The method names and parameter types in the Mapper interface are bound to the SQL statements in the Mapper.xml file.

  4. Mapper.xml: The Mapper.xml file is used to define SQL statements, including operations such as query, update, delete, and insert. It can also dynamically assemble parameters.

Detailed reference: MyBatis detailed explanation

2.SSM framework integration

2.1 Create database and table

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

2.2 Create project

Create project

2.3 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>com.by</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring.version>5.2.8.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.47</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
        <druid.version>1.1.0</druid.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>{spring.version}</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>{mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>{mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--jsp-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- log start -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>        
    </dependencies>
    <build>
        <plugins>
            <!-- ConfigurationTomcatplug-in -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!--The port number-->
                    <port>8080</port>
                    <!--Item name-->
                    <path>/</path>
                    <!--according toUTF-8Encode-->
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project> 

2.4 log4j.properties

log4j.rootLogger=DEBUG,A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} - %c%l%m%n 

2.5 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1111 

2.6 applicationContext-dao.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- Load configuration file -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- Database connection pool -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="{jdbc.url}" />
        <property name="username" value="{jdbc.username}" />
        <property name="password" value="{jdbc.password}" />
        <property name="driverClassName" value="{jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- letspringmanagesqlsessionfactory usemybatisandspringIntegrated package -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Database connection pool -->
        <property name="dataSource" ref="dataSource" />
        <!-- Alias-->
        <property name="typeAliasesPackage" value="com.by.pojo"></property>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.by.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans> 

2.7.applicationContext-tx.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- transaction manager -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- data source -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- notify -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- communication behavior -->
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- section -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* com.by.service.*.*(..))" />
    </aop:config>
</beans> 

2.8 applicationContext-service.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- scanningservicetarget coverage -->
    <context:component-scan base-package="com.by.service"></context:component-scan>
</beans> 

2.9 springmvc.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Configuration creation spring Container packages to scan -->
    <context:component-scan base-package="com.by.controller"></context:component-scan>

    <!-- Configure view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans> 

2.10 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--ConfigurationSpringlistener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- solvepostGarbled characters -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- springmvcfront-end controller -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- intercept/,For example:/user/add  -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app> 

2.11 pojo

public class Account {
    private Integer id;
    private String name;
    private Double money;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
} 

2.12 mapper

public interface AccountMapper {
    List<Account> selectAccount();
} 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.AccountMapper">
    <select id="selectAccount" resultType="Account">
        select * from account
    </select>
</mapper> 

2.13 service

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public List<Account> selectAccount() {
        return accountMapper.selectAccount();
    }
} 

2.14 controller

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/selectAccount")
    public String selectAccount(Model model){
        List<Account> list = accountService.selectAccount();
        model.addAttribute("list",list);
        return "select_account";
    }
} 

2.15 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>Check all accounts</h2>
<table width="30%" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>money</th>
    </tr>
    <c:forEach var="list" items="{list}">
        <tr>
            <td>{list.id}</td>
            <td>{list.name}</td>
            <td>{list.money}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html> 

2.16 Testing

Test

2.17 Project directory structure

Directory structure

3. Problems to be reformed

We found that the reason why we can't do without the xml configuration file now is because we have a very critical configuration. If it can also be configured with annotations, then we can get rid of the xml file:

3.1 jdbc configuration

<context:property-placeholder location="classpath:db.properties">
</context:property-placeholder>
<!--data source-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 
      destroy-method="close">
    <property name="url" value="{jdbc.url}" />
    <property name="username" value="{jdbc.username}" />
    <property name="password" value="{jdbc.password}" />
    <property name="driverClassName" value="{jdbc.driver}" />
    <property name="maxActive" value="10" />
    <property name="minIdle" value="5" />
</bean> 

3.2 mybatis configuration

 <!--sqlSessionfactory-->
    <bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="typeAliasesPackage" value="com.by.pojo"></property>
    </bean>

    <!--ConfigurationMapperScanscanningmapperinterface,And hand the generated proxy class tospringto manage-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.by.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sessionFactoryBean"></property>
    </bean> 

3.3 transactional configuration

 <bean id="transactionManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- turn onspringSupport for annotation transactions -->
    <tx:annotation-driven transaction-manager="transactionManager"/> 

3.4 service configuration

 <!--scanningservice-->
    <context:component-scan base-package="com.by.service"></context:component-scan> 

3.5 springmvc configuration

<!--Configurationspringmvcpackages to scan-->
    <context:component-scan base-package="com.by.controller,com.by.exception"></context:component-scan>

    <!--Enable annotation driver:ConfigurationhandlerMappingandhandlerAdapter-->
    <mvc:annotation-driven conversion-service="cs"></mvc:annotation-driven>

    <!--Configure date converter-->
    <bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.by.converter.MyDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--Configure view resolver-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--Configuration file upload parser-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5242880" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!--resource mapper:No need to release directlydispatcherServletto deal with-->
    <mvc:resources location="/head/" mapping="/head/**"/>

    <!--Configure interceptor-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/account/**"/>
            <mvc:exclude-mapping path="/account/login"></mvc:exclude-mapping>
            <bean class="com.by.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors> 

3.6 servlet configuration

<!--Configure listener:monitortomcatstart up,loadspringConfiguration file-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<!--front controller-->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<!--filter-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping> 

4. Relevant explanations

4.1 Correspondence between related comments and xml

Annotation Location Corresponding XML tag Function
@Configuration Class Declare the current class as a configuration class, which is equivalent to Spring configuration in xml form
@ComponentScan Class <context:component-scan> Used to scan Component
@Bean Method <bean> Declare the return value of the current method as a bean
@PropertySource Class <context:property-placeholder> Used to load configurations in *.properties files
@Import Class <import> Used to import configuration classes or some classes that need to be preloaded

4.2 @Configuration

  • Function: used to specify that the current class is a spring configuration class, which can replace the web.xml configuration file

  • Example:

    /**
     * springconfiguration class
     */
    @Configuration
    public class SpringConfiguration{
    } 
    

4.3 @ComponentScan

  • effect:

Used to specify the packages to be scanned by spring when initializing the container. Function and in spring's xml configuration file: <context:component-scan base-package="com.by"/>It's the same.

  • Attributes:

  • basePackages: used to specify the packages to be scanned. It has the same effect as the value attribute in this annotation.

  • Sample code

    /**
     * springconfiguration class
     */
    @Configuration
    @ComponentScan(basePackages = "com.by")//Equivalent to<context:component-scan>
    public class SpringConfiguration{
    } 
    

4.4 @Bean

  • effect:

This annotation can only be written on a method, indicating that an object is created using this method and placed in the spring container. Function and in spring's xml configuration file: <bean/>It's the same.

  • Attributes:

  • name: Specify a name (i.e. bean's id) for the object created by the current @Bean annotation method.

  • Sample code

    public class Dog {
        private String nam;
        private Integer age;
        //set get......
    } 
    
    @Bean
    public Dog dog(){
        Dog dog = new Dog();
        dog.setNam("Ergou");
        dog.setAge(18);
        return dog;
    } 
    

4.5 @PropertySource

  • effect:

Used to load configurations in *.properties files. Function and in spring's xml configuration file: <context:property-placeholder location="">It's the same.

  • Attributes:

  • value[]: used to specify the properties file location. If it is on the classpath, you need to write classpath:

  • Sample code

    #config.properties
    nam=Ergou
    age=18 
    
    @PropertySource("classpath:config.properties")
    public class SpringConfiguration {
    
        @Value("{nam}")
        private String nam;
        @Value("{age}")
        private Integer age;
    
        @Bean
        public Dog dog(){
            Dog dog = new Dog();
            dog.setNam(nam);
            dog.setAge(age);
            return dog;
        }
    } 
    

4.6 @Import

  • effect:

The @Import annotation is used to import configuration classes or some classes that need to be preloaded. Function and in spring's xml configuration file: <import resource=""></import>It’s the same.

  • Attributes:

  • value[]: Bytecode used to specify other configuration classes.

  • Sample code

    @Configuration
    @ComponentScan(basePackages = "com.by")
    @Import({Configuration_Other.class})
    public class SpringConfiguration {
    
    }
    
    @PropertySource("classpath:config.properties")
    public class Configuration_Other {
    
    } 
    

5.Spring’s pure annotation configuration

5.1 JdbcConfig

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;

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

    @Bean("dataSource")
    public DataSource getDatasource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
} 

5.2 MybatisConfig

 import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(
             DataSource dataSource){
        SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource);
        ssfb.setTypeAliasesPackage("com.by.pojo");
        return ssfb;
    }
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc=new MapperScannerConfigurer();
        msc.setBasePackage("com.by.mapper");
        return msc;
    }
} 

5.3 TxConfig

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;

public class TxConfig {

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
} 

5.4 SpringConfig

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@Import({MyBatisConfig.class, JdbcConfig.class, TxConfig.class})
//Equivalent<context:component-scan base-package="com.by"/>`
@ComponentScan(value = "com.by.service")
//Equivalent to<tx:annotation-driven />,beanThe name is taken by defaulttransactionManager
@EnableTransactionManagement
public class SpringConfig {

} 

5.5 SpringMvcConfig

import com.by.converter.MyDateConverter;
import com.by.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
//Equivalent to<context:component-scan base-package="com.by.controller>
@ComponentScan("com.by.controller")
//Equivalent to<mvc:annotation-driven></mvc:annotation-driven>
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/pages/"); // Set the directory where the view file is located
        viewResolver.setSuffix(".jsp"); // Set the view file suffix name
        return viewResolver;
    }

    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();

        commonsMultipartResolver.setMaxInMemorySize(5242880);
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        return commonsMultipartResolver;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new MyDateConverter());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/head/**").addResourceLocations("/head/");
    }
} 

5.6 WebConfig

 import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

/**
 * When a class is extendedAbstractAnnotationConfigDispatcherServletlnitializerand deploy it to ServletContainer time,
 * The container will automatically discover it,and use it to configureServletenvironment
 */
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    //loadSpringConfiguration class
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    //loadSpringMVCConfiguration class
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    //set upSpringMVCRequest address blocking rules
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //set uppostRequest Chinese garbled filter
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");
        return new Filter[]{filter};
    }
} 

5.7 Delete xml configuration file

xml configuration

5.8 Modify web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>