SSM从入门到放弃03:集成SSM三大框架——核心配置文件

本文详细介绍了如何在SSM框架中进行核心配置,包括Spring、MyBatis和SpringMVC的整合过程。从数据源配置、SqlSessionFactory设置,到业务层和服务层的集成,以及控制层的MVC模式开启,提供了完整的配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xml配置好之后,我们需要配置SSM的核心配置文件,此处参考文章https://cloud.tencent.com/developer/article/1039207 在这篇文章中作者按照层次分成了多个配置文件,在此我将尽量简化配置文件的数量

首先回顾一下我们的文件架构:

  • src
    • main
      • java 存放java文件,类、接口等
      • resources 存放资源文件,mapper、配置文件等
      • webapp 存放与web相关的所有文件,静态资源(图片、js、css)、jsp、html等
    • test
  • pom.xml

根据上面的架构,我们将本文所讲的所有配置文件存放在resources中。

新建spring-config.xml,如果为了方便,可以在IDEA中,右击resources - New - XML Configuration File - Spring Config ,如果你没有找到Spring Config,说明pom.xml中没有配置Spring的外部依赖,或这WEB-INF的lib目录下无Spring相关依赖包。
在这里插入图片描述

在自动生成的文件中,有一个十分简洁清晰的结构,xml标签和beans标签,在Spring中,主要使用bean来装配所有需要的组件

先po出代码

<?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:tx="http://www.springframework.org/schema/tx"
       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/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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 1. 持久层集成 -->
    <!-- 1.1 引入外部配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 1.2 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${mysql.driver}" />
        <property name="jdbcUrl" value="${mysql.url}" />
        <property name="user" value="${mysql.uid}" />
        <property name="password" value="${mysql.password}" />
        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="${mysql.maxPoolSize}" />
        <property name="minPoolSize" value="${mysql.minPoolSize}" />
        <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
        <property name="acquireIncrement" value="${mysql.acquireIncrement}"></property>
        <!-- 初始连接池大小 -->
        <property name="initialPoolSize" value="${mysql.initialPoolSize}"></property>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="${mysql.checkTimeout}" />
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="${mysql.acquireRetryAttempts}" />
    </bean>

    <!-- 1.3 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.qdsygk.ams.**.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/**/*Dao.xml" />
    </bean>

    <!-- 1.4 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.qdsygk.ams.**.dao" />
    </bean>


    <!-- 2. 业务层集成 -->
    <!-- 2.1 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.qdsygk.ams.**.service" />

    <!-- 2.2 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 2.3 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />


    <!-- 3. 控制层集成 -->
    <!-- 3.1 开启SpringMVC注解模式 -->
    <mvc:annotation-driven />

    <!-- 3.2 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler />

    <!-- 3.3 配置jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--指定视图渲染类 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <!--自动添加到路径中的前缀 -->
        <property name="prefix" value="/views/" />
        <!--自动添加到路径中的后缀 -->
        <property name="suffix" value=".jsp" />
        <!--设置所有视图的内容类型,如果视图本身设置内容类型视图类可以忽略 -->
        <property name="contentType" value="text/html;charset=UTF-8" />
    </bean>

    <!-- 3.4 扫描web相关的controller -->
    <context:component-scan base-package="com.qdsygk.ams.**.web" />

</beans>

数据持久层的集成

持久层的集成,主要是将MyBatis集成进来,并且配置与数据库的连接

首先介绍一下context:property-placeholder的作用,你可以理解成引入了一个外部文件,犹如java中的import、jsp中的include、bash中的source。

我们单独写一个关于数据库的配置文件,将它命名为db.properties,用来指明需要连接的url、user、password等等配置(看有文章提到如果mysql.uid单纯写成user,会与系统中的用户变量冲突,导致误把系统用户当成数据库用户,比如可能你写的是user=root,而你的系统用户是Administrator,此时有可能会按照Administrator去访问数据库)

注意下面等号左边的都是变量一般的存在,你可以随意取名。

#mysql
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/ams
mysql.uid=root
mysql.password=root
mysql.acquireIncrement=5
mysql.initialPoolSize=10
mysql.minPoolSize=5
mysql.maxPoolSize=20
mysql.checkTimeout=10000
mysql.acquireRetryAttempts=3

在使用context:property-placeholder引入db.properties之后,我们便可以使用${}去调用。

    <context:property-placeholder location="classpath:db.properties"/>

接下来是配置数据源,数据源需要的便是我们引用的数据库配置。要问能否不引入外部配置文件,直接在这里写配置可不可以。当然可以。只是改起来相.对.不.便.利.。

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${mysql.driver}" />
        <property name="jdbcUrl" value="${mysql.url}" />
        <property name="user" value="${mysql.uid}" />
        <property name="password" value="${mysql.password}" />
        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="${mysql.maxPoolSize}" />
        <property name="minPoolSize" value="${mysql.minPoolSize}" />
        <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
        <property name="acquireIncrement" value="${mysql.acquireIncrement}"></property>
        <!-- 初始连接池大小 -->
        <property name="initialPoolSize" value="${mysql.initialPoolSize}"></property>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="${mysql.checkTimeout}" />
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="${mysql.acquireRetryAttempts}" />
    </bean>

接下来是配置sql会话工厂,在这里你可以理解成,我们把mybatis框架集成进来,把数据源集成进来,把写sql的xml集成进来,在写sql的xml中为了引用实体的便利性,还可以配置一个别名。

先po一下mybatis的配置文件,为了方便,可以右击resources - New - 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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />
        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>

    <!-- Continue going here -->

</configuration>

然后是sql会话工厂的bean

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.qdsygk.ams.**.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/**/*Dao.xml" />
    </bean>

最后,将mybatis与java的接口进行集成,有了这个配置,才可以识别到某package中的interface是个持久层接口,才可以与sql-xml中的namespace进行映射

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.qdsygk.ams.**.dao" />
    </bean>

业务逻辑层的集成

业务层的集成主要是开启事务,以@Service注解的方式指定某个类为业务层类。(我这里解释的也不是很明确,欢迎自查和补充……)

    <!-- 2.1 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.qdsygk.ams.**.service" />

    <!-- 2.2 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 2.3 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

网络控制层的集成

控制层的集成还是比较清晰的

  1. 开启MVC模式:SpringMVC
  2. 静态资源的servlet
  3. 配置JSP
  4. 扫描@Controller注解的类,该类即为控制层类
    <!-- 3.1 开启SpringMVC注解模式 -->
    <mvc:annotation-driven />

    <!-- 3.2 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler />

    <!-- 3.3 配置jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--指定视图渲染类 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <!--自动添加到路径中的前缀 -->
        <property name="prefix" value="/views/" />
        <!--自动添加到路径中的后缀 -->
        <property name="suffix" value=".jsp" />
        <!--设置所有视图的内容类型,如果视图本身设置内容类型视图类可以忽略 -->
        <property name="contentType" value="text/html;charset=UTF-8" />
    </bean>

    <!-- 3.4 扫描web相关的controller -->
    <context:component-scan base-package="com.qdsygk.ams.**.web" />

至此,我们的SSM便配置完成了~

如果你还需要一个日志配置

创建一个logback.xml就ok了

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值