Spring整合SpringMvc和Mybatis配置

一、spring配置

1、spring-aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--配置扫描器必须引入的xmlns 属性: xmlns:context="http://www.springframework.org/schema/context" -->
<!--配置aop的通知必须引入的xmlns 属性: xmlns:aop="http://www.springframework.org/schema/aop" -->
<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"
       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.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

    <!--开启自动扫描-->
    <context:component-scan base-package="com.donleo.ssm"/>
    <!--<context:component-scan base-package="com.donleo.ssm.service"/>-->

    <!--开启aop自动动态代理-->
    <aop:aspectj-autoproxy/>

</beans>

2、spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--配置扫描器必须引入的xmlns 属性: xmlns:context="http://www.springframework.org/schema/context" -->
<!--配置aop的通知必须引入的xmlns 属性: xmlns:aop="http://www.springframework.org/schema/aop" -->
<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/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <!--引入jdbc配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--Spring整合Mybatis-->
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--基本配置-->
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.diverClassName}"/>

        <!--扩展配置-->
        <!--监控统计用filters:stat 日志用filters:log4j 防御sql注入用filters:wall-->
        <property name="filters" value="${filters}"/>
        <!--最大连接池数量-->
        <property name="maxActive" value="${maxActive}"/>
        <!--初始化建立物理连接的个数-->
        <property name="initialSize" value="${initialSize}"/>
        <!--获取连接时最长的等待时间-->
        <property name="maxWait" value="${maxWait}"/>
        <!--最小连接池数量-->
        <property name="minIdle" value="${minIdle}"/>
        <!--有两个含义 1.Destroy 线程会检测连接的时间 2.testWhileIdle的判断依据-->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
        <!--Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于minEvictableIdleTimeMillis,
            则关闭当前连接-->
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>
        <!--用来检测连接是否的sql,要求是一个查询语句。在mysql中通常设置为SELECT 'X'-->
        <property name="validationQuery" value="${validationQuery}"/>
        <!--申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery连接是否有效-->
        <property name="testWhileIdle" value="${testWhileIdle}"/>
        <!--申请连接时执行validationQuery检测连接是否有效 这个配置会降低性能-->
        <property name="testOnBorrow" value="${testOnBorrow}"/>
        <!--归还连接时执行validationQuery检测连接是否有效 这个配置会降低性能-->
        <property name="testOnReturn" value="${testOnReturn}"/>
        <!--要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true-->
        <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}"/>
        <!--对于建立连接超过removeAbandonedTimeout的连接强制关闭-->
        <property name="removeAbandoned" value="${removeAbandoned}"/>
        <!--指定连接建立多长就被强制关闭-->
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
        <!--指定发生removeabandoned时,是否记录当前线程的堆栈信息到日志中-->
        <property name="logAbandoned" value="${logAbandoned}"/>

    </bean>

    <!--******************配置事物********************-->
    <!--**************基于配置文件声明事物***************-->
    <!--
        一、基于配置文件分为三步:
        1、注册事物
        2、配置事物规则
        3、开启AOP参与事物
        二、基于注解方式配置事物,需要在方法上加上@Transactional注解,并配置相关属性
    -->
    <!--1.注册事物(配置事物管理器)-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2.事物配置规则(配置事物属性,需要事物管理器)-->
    <tx:advice id="adviceId" transaction-manager="transactionManager">
        <tx:attributes>
            <!--propagation="REQUIRED"代表支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择-->
            <!--propagation="SUPPORTS" 支持当前事务,如果当前没有事务,就以非事务方式执行。 -->
            <!--read-only   事务是否只读?-->
            <tx:method name="find*" read-only="true"/>
            <tx:method name="select*" read-only="true"/>
            <tx:method name="save*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="delete*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="update*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="insert*" read-only="false" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--3.开启AOP参与事物(配置事物切点,把事物属性和切点关联起来)-->
    <aop:config>
        <!--配置切入点 expression:配置参与事物的类-->
        <aop:pointcut id="pointCutId" expression="execution(* com.donleo.ssm.service.impl.*.*(..))"/>
        <!--配置切面 aop:advisor标签就是把上面我们所配置的事务管理两部分属性整合起来作为整个事务管理-->
        <aop:advisor advice-ref="adviceId" pointcut-ref="pointCutId"/>
    </aop:config>


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

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

3、spring-mvc.xml(spring整合MVC配置)

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

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <!-- 简化配置:
        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
    -->
    <mvc:annotation-driven/>

    <!-- 2.静态资源默认servlet配置
        (1)加入对静态资源的处理:js,gif,png
        (2)允许使用"/"做整体映射
        配置了该配置就不用配置下面这个了
         <mvc:resources mapping="/js/**" location="/js/"/>
     -->
    <mvc:default-servlet-handler/>


    <!-- 3.配置jsp 显示ViewResolver -->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 根据URL中的文件扩展名确定MIME(如userList.xml,userList.json) -->
        <property name="favorPathExtension" value="true"/>
        <!-- 则根据请求参数的值确定MIME类型,默认的请求参数是format,可以通过parameterName属性指定一个自定义的参数  -->
        <property name="favorParameter" value="true"/>
        <!-- 则采用Accept请求报文头的值确定MIME类型。由于不同的浏览器产生的Accept头都是不一样的,所以一般不建议采用Accept确定MIME类型 -->
        <property name="ignoreAcceptHeader" value="true"/>
        <property name="useJaf" value="false"/>
        <property name="defaultContentType" value="text/html"/>
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json"/>
                <entry key="xml" value="application/xml"/>
            </map>
        </property>
    </bean>

    <!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="contentNegotiationManager" ref="contentNegotiationManager" />

        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/views/" />
                    <property name="suffix" value=".jsp" />
                    <property name="contentType" value="text/html; charset=UTF-8"/>
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
                </bean>
            </list>
        </property>

        <property name="defaultViews">
            <list>
                <!– for application/json –>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                    <property name="extractValueFromSingleKeyModel" value="true" />
                    <property name="objectMapper">
                        <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                            <property name="serializationInclusion">
                                <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                            </property>
                        </bean>
                    </property>
                </bean>

                <!– for application/xml –>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller">
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                            <property name="autodetectAnnotations" value="true"/>
                            <property name="streamDriver">
                                <bean class="com.thoughtworks.xstream.io.xml.StaxDriver" />
                            </property>
                        </bean>
                    </property>
                </bean>
            </list>
        </property>
    </bean>-->


   <!-- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="viewResolvers">
            <list>
                <bean
                        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"></property>
                    <property name="suffix" value=".jsp"></property>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                        class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                </bean>
            </list>
        </property>
    </bean>-->


    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.donleo.ssm.controller"/>

    <context:component-scan base-package="com.donleo.ssm.service"/>


    <!-- 接口跨域配置-->
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="*"
                     allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                     allowed-headers="Content-Type,  Content-Length, Authorization, Accept, X-Requested-With, yourHeaderFeild"
                     allow-credentials="true"/>
    </mvc:cors>

</beans>

4、web.xml配置

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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_3_0.xsd"
         version="3.0">
    <display-name>Archetype Created Web Application</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!--配置编码过滤器,主要用来解决乱码问题-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <!-- 默认匹配所有的请求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 跨域请求 -->
     <filter>
       <filter-name>CrossDomainFilter</filter-name>
       <filter-class>com.donleo.ssm.filter.CrossDomainFilter</filter-class>
       <init-param>
         <param-name>IsCross</param-name>
         <param-value>true</param-value>
       </init-param>
     </filter>

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


</web-app>

二、Mybatis配置

1、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" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

三、其它配置

1、jdbc.properties

jdbc.diverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/stmg_dev?serverTimezone=UTC&characterEncoding=utf-8&nullCatalogMeansCurrent=true
jdbc.username=root
jdbc.password=123456



------------------------------------------------------------------------------------------
#配置扩展插件 监控统计用filters:stat 日志用filters:log4j 防御sql注入用filters:wall
filters:stat

#最大连接池数量  初始化建立物理连接的个数  获取连接时最长的等待时间  最小连接池数量  maxIdle已经弃用
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
#maxIdle:15

#有两个含义 1.Destroy 线程会检测连接的时间 2.testWhileIdle的判断依据
timeBetweenEvictionRunsMillis:60000

#Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于minEvictableIdleTimeMillis,则关闭当前连接
minEvictableIdleTimeMillis:300000

#用来检测连接是否的sql,要求是一个查询语句。在mysql中通常设置为SELECT 'X'
validationQuery:SELECT 'x'

#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery连接是否有效
testWhileIdle:true

#申请连接时执行validationQuery检测连接是否有效 这个配置会降低性能
testOnBorrow:false

#归还连接时执行validationQuery检测连接是否有效 这个配置会降低性能
testOnReturn:false

#要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true
maxOpenPreparedStatements:20

#对于建立连接超过removeAbandonedTimeout的连接强制关闭
removeAbandoned:true

#指定连接建立多长就被强制关闭
removeAbandonedTimeout:1800

#指定发生removeabandoned时,是否记录当前线程的堆栈信息到日志中
logAbandoned:true

2、log4j.properties

log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
作者:donleo123
本文如对您有帮助,还请多推荐下此文,如有错误欢迎指正,相互学习,共同进步。
原文地址:https://www.cnblogs.com/donleo123/p/14067899.html