使用IDEA实现SSM整合MavenSpringMybatisSpringMvc

41次阅读

共计 11878 个字符,预计需要花费 30 分钟才能阅读完成。

我是阿福,公众号「阿福聊编程」作者, 一个在后端技术路上摸盘滚打的程序员 ,在进阶的路上,共勉!

文章已收录在 JavaSharing 中,包含 Java 技术文章,面试指南,资源分享。

本文是基于 Maven 工程实现 SSM 整合,主要是通过 XML 实现三大框架的整合,可能有的小伙伴会说 XML 早就过时了,现在人们都使用注解开发,但是不是这么认为,我个人觉得你 XML 整合会了,注解能不会吗?开干!!!!

SSM 整合总体思路

Spring 和 MyBatis 整合

整合 JAR 包

<dependencies>
        <!-- Spring 依赖 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cglib/cglib -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- MySQL 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-Java</artifactId>
            <version>5.1.3</version>
        </dependency>
        <!-- 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!-- MyBatis 与 Spring 整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
        </dependency>

        <!-- Spring 进行 JSON 数据转换依赖 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.2</version>
        </dependency>
        <!-- JSTL 标签库 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- junit 测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 引入 Servlet 容器中相关依赖 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSP 页面使用的依赖 -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1.3-b06</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

创建 Spring 的配置文件

  • spring-persist-mybatis.xml — 数据源相关的配置
  • spring-persist-tx.xml — 事务相关的配置
  • spring-web-mvc.xml —SpringMvc 相关的配资

创建 jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3307/crowdfunding?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

创建 log4j.properties

log4j.rootLogger=DEBUG,myConsole
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.Target=System.out
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n

配置数据源

在配置文件 spring-persist-mybatis.xml,分为两步:加载外部的属性文件,配置数据源

    <!-- 加载外部的属性文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driver}"></property>
    </bean>

数据源测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:/spring/spring-persist-mybatis.xml"})
public class AtcrowFundingAdminTest {
  @Autowired
  public DataSource dataSource;
  @Test
  public void DataSourceTest() throws Exception{System.out.println("数据源:"+dataSource.getConnection());
  }
} 

创建 MyBatis 全局配置文件

配置 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>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用 jdbc 的 getGeneratedKeys 获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

配置 SqlSessionFactoryBean

在配置文件:spring-persist-mybatis.xml,分为两步:配置 SqlSessionFactoryBean,配置 mybatis 的包扫描器

<!-- 配置 SqlSessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 装配数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--mybatis 配置文件所在的位置 -->
        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property>
        <!-- 配置 mapper 所在的文件位置 -->
        <property name="mapperLocations" value="classpath:/mybatis/mapper/*Mapper.xml"></property>
    </bean>
    <!-- 配置 mybatis 的包扫描器 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置 mapper 所在的包 -->
        <property name="basePackage" value="com.zfcoding.dao"></property>
    </bean>

到这里 spring-persist-mybatis.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-4.0.xsd">
    <!-- 注册组件包扫描,把类上标注了 @Controller @Service @Repository @Component 都会自动加入到 Spring 容器中 -->
    <context:component-scan base-package="com.zfcoding"></context:component-scan>
    <!-- 加载外部的属性文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driver}"></property>
    </bean>
    <!-- 配置 SqlSessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 装配数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--mybatis 配置文件所在的位置 -->
        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property>
        <!-- 配置 mapper 所在的文件位置 -->
        <property name="mapperLocations" value="classpath:/mybatis/mapper/*Mapper.xml"></property>
    </bean>
    <!-- 配置 mybatis 的包扫描器 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置 mapper 所在的包 -->
        <property name="basePackage" value="com.zfcoding.dao"></property>
    </bean>
</beans>

配置声明式事务

所在配置文件:spring-persist-tx.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务属性 -->
        <tx:attributes>
            <!-- 将查询方法设置为只读 -->
            <tx:method name="get*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="count*" read-only="true"/>

            <!-- 给增删改方法设置属性 -->
            <!-- propagation:配置传播行为,REQUIRES_NEW 表示必须工作在自己新开的事务中,不受其他事务回滚影响 -->
            <!-- rollback-for:配置回滚的异常,默认是根据运行时异常回滚,为了抛出编译时异常也回滚,设置为 java.lang.Exception -->
            <tx:method name="save*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
            <tx:method name="remove*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>

        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切面 -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut id="txPointCut" expression="execution (* com.zfcoding.service..*.*(..))"/>
        <!-- 将事务通知和切入点表达式关联起来 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor>
    </aop:config>
</beans>

SpringMVC

配置 spring-web-mvc.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"
       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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 开启注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 配置视图解析器   -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <context:component-scan base-package="com.zfcoding.controller"></context:component-scan>
</beans>

配置 web.xml

配置监听器(contextConfigLocation)加载 spring-persist-mybatis.xml,spring-persist-tx.xml 配置文件,

配置 DispatchServlet 加载 spring-web-mvc.xml 配置文件

配置过滤器编码的格式

这些文件在项目启动的时候加载到 Sping 容器当中。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <!-- 配置监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 项目启动加载 spring 的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring/spring-persist-*.xml</param-value>
    </context-param>
    <!-- 配置 DispatchServlet-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:spring/spring-web-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <!-- 配置过滤器 -->
    <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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

创建 Controller 类测试

@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    public AdminService adminService;

    @RequestMapping("/findall")
    public String findAll(Model model) {List<AdminBean> list = adminService.findAllAdmin();
        model.addAttribute("list", list);
        return "admin";
    }
}

请求路径:http://localhost:8080/ssm_war_exploded/admin/findall.action

页面响应

AdminBean{id=1, loginAcct=’admin’, userPswd=’123′, userName=’ 你好 ’, email=”, createTime=’null’}

到此 SSM 基本功能的整合已经完成了。

源码下载

正文完
 0