继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Maven多模块项目搭建+SSM框架整合(三、配置文件添加,服务层测试)

song先生
关注TA
已关注
手记 41
粉丝 218
获赞 1546

四、配置文件添加

我们需要添加相关配置文件applicationContext.xml、jdbc.properties、log4j.properties、mybatis-config.xml、spring-mvc.xml
图片描述
(1)applicationContext.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"
       xmlns:p="http://www.springframework.org/schema/p"
       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/aop
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- jdbc配置 -->
    <context:property-placeholder location="classpath:config/jdbc.properties" />

    <!-- 自动将Service层注入-->
    <context:component-scan base-package="com.songci.mytest_one.service" />

    <!-- dbcp数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <!--这里如果写成${jdbc.driver},就会出现加载jdbc驱动失败的问题,暂时不清楚什么原因-->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- 连接池最大使用连接数 -->
        <property name="maxActive" value="20"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="1"/>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000"/>
        <!-- 连接池最大空闲 -->
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="3"/>
        <!-- 自动清除无用连接 -->
        <property name="removeAbandoned" value="true"/>
        <!-- 清除无用连接的等待时间 -->
        <property name="removeAbandonedTimeout" value="180"/>
        <!-- 连接属性 -->
        <property name="connectionProperties" value="clientEncoding=UTF-8"/>
    </bean>

    <!-- mybatis的配置文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"/>
    </bean>

    <!-- spring与mybatis整合配置,扫描所有dao 和所有mapper文件 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.songci.mytest_one.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 写操作 -->
            <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"/>
            <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"/>
            <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT"/>
            <tx:method name="batch*" propagation="REQUIRED" isolation="DEFAULT"/>

            <!-- 读操作 -->
            <tx:method name="load*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
            <tx:method name="get*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>

            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pc" expression="execution(public * com.songci.mytest_one.service.*.*(..))"/>
        <!--把事务控制在Service层-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
    </aop:config>
</beans>

(2)jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

(3)log4j.properties

### set log levels ###
#log4j.rootLogger = debug , stdout , D , E
log4j.rootLogger = DEBUG , stdout

###  output to the console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

### Output to the log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${mytest_one.root}/WEB-INF/logs/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd 
log4j.appender.ServerDailyRollingFile.File=${mytest_one.root}/WEB-INF/logs/error.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout 
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern= %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n 
log4j.appender.ServerDailyRollingFile.Append=true

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.org.mybatis=DEBUG  
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout
com.ng.mapper=DEBUG

(4)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="com.songci.mytest_one.model" />
    </typeAliases>

</configuration>

(5)spring-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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-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/aop
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 扫描controller(controller层注入) -->
    <context:component-scan base-package="com.songci.mytest_one.controller"/>

    <!-- 启动注解支持 -->
    <mvc:annotation-driven />

    <!-- 静态资源 -->
    <!--<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>-->
    <!--<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/WEB-INF/image/" mapping="/image/**"/>-->

    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="2"/>
    </bean>

    <!-- 避免IE在ajax请求时,返回json出现下载 -->
    <bean id="jacksonMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!--Spring3.1开始的注解 HandlerMapping -->
    <!--3.1之后必须存在, 不解-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <!--Spring3.1开始的注解 HandlerAdapter -->
    <!--Spring3.1之前的注解 HandlerAdapter org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter"/>
                <!-- json转换器 -->
            </list>
        </property>
    </bean>
    <!--文件上传限制-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="5242880"/>
    </bean>

</beans>

六、写测试类

图片描述

package com.songci.mytest_one.test;

import com.songci.mytest_one.model.Student;
import com.songci.mytest_one.service.StudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by songl on 2017/8/9.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:config/applicationContext.xml")
public class ServiceTest {
    @Resource
    private StudentService studentService;
    @Test
    public void addTest() throws Exception {
        Student student=new Student();
//        student.setId(new Integer("1"));
        student.setName("王同学");
        student.setSex(false);
        student.setAddress("北京");
        System.out.println(studentService.addStudent(student));
    }
    @Test
    public void deleteTest()throws Exception{
        System.out.println(studentService.deleteStudentById(1));

    }
    @Test
    public void updateTest()throws Exception{
        Student student=new Student();
        student.setId(new Integer("4"));
        student.setAddress("台湾");
        System.out.println(studentService.updateStudentById(student));
    }
    @Test
    public void select()throws Exception{
//        Student student=new Student();
//        student.setId(new Integer("1"));
        List<Student> list=studentService.findAllStudent(null);
        for (Student s:list){
            System.out.println(s.toString());
        }

    }
}
相关代码在GitHub上,包括数据库sql文件

GitHub地址:https://github.com/iamsongci/mytest_one

将持续更新 ~~~ 未完待续~~~

下篇Maven-maven多模块项目搭建+SSM框架整合(四、Ajax异步获取数据,jquery动态添加)

请将你想了解的技术写在下面评论里,我将会在以后文章中写入有关内容

如果感觉文章不错记得点赞哦,谢谢支持。

打开App,阅读手记
12人推荐
发表评论
随时随地看视频慕课网APP

热门评论

插入数据库的数据老是乱码,jdbc文件里面的url也设置了utf-8格式,实在搞不懂,数据库和表都是utf-8格式

辛苦楼主 

我是初学者 - 对SSM这种框架懂得基本为0 - 看您的博客还有有点难度的,如果可以麻烦写的在细致一些哈 。

查看全部评论