This is the 14th day of my participation in the August More Text Challenge

Basic dependence

  1. Relevant jars

    • Jackson
    • Spring, SpringMVC, Spring JDBC
    • Mybatis, mybatis – spring
    • Druid connection pool
  2. pom.xml

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.8. RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.8. RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.</version>
    </dependency>
    Copy the code

Using XML Configuration

  1. The web.xml configuration

    Configure DispatcherServlet and set up to start loading

    
            
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             id="WebApp_ID" version="3.1">
        <servlet>
            <servlet-name>app</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-config.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>app</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    Copy the code
  2. spring-config.xml

    Configure MyBatis, data source, and MapperSanner

    
            
    <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"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <! - configure MyBatis -- -- >
        <bean id="sqlSessionFactory"
              class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <! -- Mybatis config file -->
            <property name="configLocation"
                      value="classpath:mybatis-config.xml" />
            <! --mapper.xml -->
            <property name="mapperLocations"
                      value="classpath:mapper/*.xml" />
        </bean>
        <! -- Configure data source -->
        <! -- read the db. The properties - >
        <context:property-placeholder location="classpath:db.properties" />
        <bean id="dataSource"
              class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName"
                      value="${mysql.driver}" />
            <property name="url"
                      value="${mysql.url}" />
            <property name="username" value="${mysql.username}" />
            <property name="password" value="${mysql.password}" />
        </bean>
        <! - the configuration MapperScanner -- -- >
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName"
                      value="sqlSessionFactory" />
            <! --@Mapper Scan package -->
            <property name="basePackage" value="cade.mapper" />
        </bean>
        <! -- Configure Component scan -->
        <context:component-scan
                base-package="cade.controller" />
        <context:component-scan
                base-package="cade.service" />
        <! -- Configure MVC annotation support -->
        <mvc:annotation-driven />
         <! Configure static resource mapping -->
        <mvc:resources mapping="/static/**" location="classpath:static/" />
    </beans>
    Copy the code
  3. mybatis-config.xml

    
            
    <! DOCTYPEconfiguration  PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <! -- Alias configuration -->
        <typeAliases>
            <package name="cade.entity" />
        </typeAliases>
    </configuration>
    Copy the code

Write test code

  1. UserMapper

    @Mapper
    public interface UserMapper {
        List<User> listUsersAll(a);
    }
    Copy the code
    <mapper namespace="cade.mapper.UserMapper">
        <select id="listUsersAll" resultType="user">
            select * from user
        </select>
    </mapper>
    Copy the code
  2. UserService

    @Service
    public class UserServiceImpl implements UserService {
    
        private final UserMapper userMapper;
    
        @Autowired
        public UserServiceImpl(UserMapper userMapper) {
            this.userMapper = userMapper;
        }
    
        @Override
        public List<User> listUsersAll(a) {
            returnuserMapper.listUsersAll(); }}Copy the code
  3. UserController

    @Controller
    public class HelloController {
    
        private final UserService userService;
    
        @Autowired
        public HelloController(UserService userService) {
            this.userService = userService;
        }
    
        @ResponseBody
        @RequestMapping("/users")
        public List<User> listUsersAll(a) {
            returnuserService.listUsersAll(); }}Copy the code
  4. Entity class

    public class User {
        String name;
        Integer age;
    	// ...
    }
    Copy the code
  5. Visit/Users to test

    [{"name":"Bill"."age":20}, {"name":"Zhang"."age":23}, {"name":"Fifty"."age":23}]
    Copy the code

Use JavaConfig for configuration

  1. The configuration class replaces web.xml

    In the Servlet 3.0 environment, the Servlet container will search implementation under the classpath javax.mail. Servlet. ServletContainerInitializer interface any class, after we use it to initialize the Servlet container

    Spring implements the above interface, implementation class called SpringServletContainerInitializer, it will in turn to search for WebApplicationInitializer any class, and delegate this class implements configuration

    , Spring 3.2 introduced a simple WebApplicationInitializer implementation class, this is AbstractAnnotationConfigDispatcherServletInitializer

    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
    
    public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protectedClass<? >[] getRootConfigClasses() {return null;
        }
    
        @Override
        protectedClass<? >[] getServletConfigClasses() {// Introduce the Spring Config configuration class
            return new Class[]{SpringConfig.class};
        }
    
        @Override
        protected String[] getServletMappings() {
            // Intercept the path
            return new String[]{"/"}; }}Copy the code
  2. The configuration class replaces Spring-config. XML and mybatis

    Use annotations to open SpringMVC and configure beans in the Spring configuration class

    @Configuration
    @ComponentScan(basePackages = {"cade.controller", "cade.service"}) / / scanning component
    @EnableWebMvc // <mvc:annotation-driven />
    public class SpringConfig implements WebMvcConfigurer {
    
        // mybatis
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory(a) {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(this.dataSource());
            // Mybatis configuration file location
            Resource mybatisConfigResource = new ClassPathResource("mybatis-config.xml");
            sqlSessionFactoryBean.setConfigLocation(mybatisConfigResource);
            Mapper. XML file location
            Resource userMapperXML = new ClassPathResource("mapper/UserMapper.xml");
            sqlSessionFactoryBean.setMapperLocations(new Resource[]{userMapperXML});
            return sqlSessionFactoryBean;
        }
    
        / / the data source
        @Bean
        public DataSource dataSource(a) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            dataSource.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / demo? useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
            dataSource.setUsername("root");
            dataSource.setPassword("cade");
            return dataSource;
        }
    
        // Mapper class scan, the same function as @mapperscan
        @Bean
        public MapperScannerConfigurer initMapperScannerConfigurer(a) {
            MapperScannerConfigurer msc = new MapperScannerConfigurer();
            msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
            msc.setBasePackage("cade.mapper");
            return msc;
        }
    
        // <mvc:resources mapping="/static/**" location="classpath:static/" />
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("/static/"); }}Copy the code