SSM 框架整合
Spring + SpringMVC + MyBatis 整合(XML 配置和纯 Java 类配置)

# SSM 框架整合

# 基本依赖

  1. 相关 Jar 包

    • Jackson
    • Spring、SpringMVC、Spring JDBC
    • mybatis、mybatis-spring
    • druid 连接池
  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.2.4</version>
    </dependency>
    

# 使用 XML 配置

  1. web.xml 配置

    配置 DispatcherServlet 并随启动加载

    <?xml version="1.0" encoding="UTF-8"?>
    <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>
    
  2. spring-config.xml

    配置 MyBatis、数据源、MapperSanner

    <?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"
           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">
        <!--配置 MyBatis-->
        <bean id="sqlSessionFactory"
              class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!--mybatis 配置文件-->
            <property name="configLocation"
                      value="classpath:mybatis-config.xml" />
            <!--mapper.xml 存放位置-->
            <property name="mapperLocations"
                      value="classpath:mapper/*.xml" />
        </bean>
        <!--配置数据源-->
        <!--读取 db.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>
        <!--配置 MapperScanner-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName"
                      value="sqlSessionFactory" />
            <!--@Mapper 扫描包-->
            <property name="basePackage" value="cade.mapper" />
        </bean>
        <!--配置 component 扫描-->
        <context:component-scan
                base-package="cade.controller" />
        <context:component-scan
                base-package="cade.service" />
        <!--配置 mvc 注解支持-->
        <mvc:annotation-driven />
         <!--配置静态资源映射-->
        <mvc:resources mapping="/static/**" location="classpath:static/" />
    </beans>
    
  3. mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!--别名配置-->
        <typeAliases>
            <package name="cade.entity" />
        </typeAliases>
    </configuration>
    

# 编写测试代码

  1. UserMapper

    @Mapper
    public interface UserMapper {
        List<User> listUsersAll();
    }
    
    <mapper namespace="cade.mapper.UserMapper">
        <select id="listUsersAll" resultType="user">
            select * from user
        </select>
    </mapper>
    
  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() {
            return userMapper.listUsersAll();
        }
    }
    
  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() {
            return userService.listUsersAll();
        }
    }
    
  4. 实体类

    public class User {
        String name;
        Integer age;
    	// ...
    }
    
  5. 访问 /users 进行测试

    [{"name":"李四","age":20},{"name":"张三","age":23},{"name":"王五","age":23}]
    

# 使用 JavaConfig 配置

  1. 配置类代替 web.xml

    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
    
    public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return null;
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            // 引入 spring config 配置类
            return new Class[]{SpringConfig.class};
        }
    
        @Override
        protected String[] getServletMappings() {
            // 拦截路径
            return new String[]{"/"};
        }
    }
    
  2. 配置类代替 spring-config.xml、mybatis.xml

    @Configuration
    @ComponentScan(basePackages = {"cade.controller", "cade.service"}) // 扫描 component
    @EnableWebMvc // <mvc:annotation-driven />
    public class SpringConfig implements WebMvcConfigurer {
    
        // mybatis
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory() {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(this.dataSource());
            // mybatis 配置文件位置
            Resource mybatisConfigResource = new ClassPathResource("mybatis-config.xml");
            sqlSessionFactoryBean.setConfigLocation(mybatisConfigResource);
            // mapper.xml 文件位置
            Resource userMapperXML = new ClassPathResource("mapper/UserMapper.xml");
            sqlSessionFactoryBean.setMapperLocations(new Resource[]{userMapperXML});
            return sqlSessionFactoryBean;
        }
    
        // 数据源
        @Bean
        public DataSource dataSource() {
            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 类扫描
        @Bean
        public MapperScannerConfigurer initMapperScannerConfigurer() {
            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/");
        }
    }
    
Comment here, be cool~

Copyright © 2020 CadeCode

Theme 2zh powered by VuePress

本页访问次数 0

Loading