一、用Maven构建基于Spring+SpringMVC+Mybatis的web项目

本系列目录 http://www.jianshu.com/p/22f3b28d974c

假设读者有能力用Maven构建WEB项目。

1. 下图是Eclipse下项目的项目结构

Paste_Image.png

2. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.albert</groupId>
    <artifactId>AlbertBlog</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>AlbertBlog Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- base setting -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.locales>zh_CN</project.build.locales>
        <project.build.jdk>1.7</project.build.jdk>

        <!-- lib versions -->
        <junit.version>4.12</junit.version>
        <spring.version>4.0.2.RELEASE</spring.version>
        <quartz.version>2.2.1</quartz.version>
        <log4j.version>1.2.14</log4j.version>
        <mysql.connector.version>5.1.21</mysql.connector.version>
        <aspectj.version>1.6.2</aspectj.version>
        <json.version>20140107</json.version>
        <jedis.version>2.6.0</jedis.version>
        <commons.logging.version>1.1.3</commons.logging.version>
        <commons.lang.version>2.6</commons.lang.version>
         <mybatis.version>3.2.6</mybatis.version>
        <javassist.version>3.18.0-GA</javassist.version>
        <druid.version>1.0.5</druid.version>
        <jackson-version>2.3.0</jackson-version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.4.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Quartz framework -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${quartz.version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${json.version}</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${jedis.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${commons.logging.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons.lang.version}</version>
        </dependency>

        
         <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>${javassist.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.0</version>
        </dependency>

        <!-- json jackson -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!--spring websocket库 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson-version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson-version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>AlbertBlog</finalName>
    </build>
</project>

pom.xml在接下来的开发中会根据需要添加依赖包。

3. applicationContext.xml

此文件中配置datasource,sessionFactory,连接池,事务

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 自动扫描 ,将带有注解的类 纳入spring容器管理 -->
    <context:component-scan base-package="com.albert"></context:component-scan>

    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:application.properties</value>
            </list>
        </property>
    </bean>

    <!-- dataSource 配置 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${ds.initialSize}"/>
        <property name="minIdle" value="${ds.minIdle}"/>
        <property name="maxActive" value="${ds.maxActive}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${ds.maxWait}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>

        <property name="validationQuery" value="SELECT 'x'"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="false"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat"/>
    </bean>

    <!-- mybatis文件配置,扫描所有mapper文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"
          p:configLocation="classpath:mybatis-config.xml"
          p:mapperLocations="classpath:com/albert/dao/*.xml"/>
    
    <!-- spring与mybatis整合配置,扫描所有dao -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.albert.dao"
          p:sqlSessionFactoryBeanName="sqlSessionFactory"/>

    <!-- 对dataSource 数据源进行事务管理 -->
   <!-- 配置事务容器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/>

    <!-- 事务管理 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 -->
            <tx:method name="insert" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
            <!-- select,count开头的方法,开启只读,提高数据库访问性能 -->
            <tx:method name="select*" read-only="true"/>
            <tx:method name="count*" read-only="true"/>
            <!-- 对其他方法 使用默认的事务管理 -->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- 事务 aop 配置 -->
    <aop:config>
        <aop:pointcut id="serviceMethods" expression="execution(* com.albert.service..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
    </aop:config>
    <!-- 开启AOP监听 只对当前配置文件有效 -->
    <aop:aspectj-autoproxy expose-proxy="true" />  
    <!-- 启用对事务注解的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

4. 配置mybatis-conf.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>  
        <typeAlias alias="Users" type="com.albert.domain.table.Users" />  
    </typeAliases>  
  
</configuration>    

5. DAO层

至此,项目配置部分基本完毕,接下来我们添加实体以及DAO层的mapper。在com.albert.domain.table包下面添加实体User.java,dao层添加相应的UserMapper.java,UserMapper.xml.(这里手动添加是为了更好的学习。接下来的模块会使用mybatis-generater自动生成modal,dao,mapper)
`
UserMapper.java

/**
 * 
 */
package com.albert.dao;

import java.util.List;

import com.albert.domain.table.Users;

/** 
* @ClassName: UserMapper 
* @Description: 
* @author albert
* @date 2017年3月6日 下午7:30:41 
*  
*/
public interface UserMapper {
    void save(Users user);
    void update(Users user);
    void delete(Integer id);
    Users findById(Integer id);
    List<Users> findAll();
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">  

<mapper namespace="com.albert.dao.UserMapper">  
      <!--这里的id一定要与上面接口里方法一一对应-->
    <insert id="save" parameterType="Users">  
        insert into t_users(uid,username,password) values(#{uid},#{username},#{password})  
    </insert>  
      
    <update id="update" parameterType="Users">  
        update t_users set username=#{username},password=#{password} where uid=#{uid}  
    </update>  
      
    <delete id="delete" parameterType="Integer">  
        delete from t_users where uid=#{uid}  
    </delete>  
      
    <select id="findById" parameterType="int" resultType="Users">  
        select uid uid,username userame,password password from t_users where uid=#{uid}  
    </select> 
 
    <select id="findAll" resultType="Users">  
        select uid uid,username username,password password from t_users  
    </select>  
</mapper>  

6. DAO层测试(Junit)

Paste_Image.png

TestSupport.java 是个抽象类,其他测试代码必须继承它

package com.albert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 
* @ClassName: TestSupport 
* @Description: junit 测试
* @author albert
* @date 2017年3月6日 下午11:11:17 
*
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public abstract class TestSupport extends AbstractJUnit4SpringContextTests {
   
    @BeforeClass
    public static void start() {
        System.out.println("测试前置处理");
    }

   
    @AfterClass
    public static void end() {
        System.out.println("测试后置处理");
    }

    /**
     * 输出记录
     */
    protected void log() {
        logger.info("测试");
    }
}

下面是JUNIT测试代码

package com.albert.test;

import javax.annotation.Resource;
import org.junit.Test;
import com.albert.TestSupport;
import com.albert.dao.UserMapper;
import com.albert.domain.table.Users;
import com.albert.service.UserService;

/** 
* @ClassName: DaoTest 
* @Description: 测试DAO层
* @author albert
* @date 2017年3月6日 下午7:50:36 
*  
*/
public class DaoTest extends TestSupport{
    @Resource
    private UserMapper userMapper;
    @Test
    public void test(){
        Users u = userMapper.findById(1);
        System.out.println(u);
    }
}

运行上面的测试代码,控制台打印了查到的结果

[INFO ] 2017-03-07 00:28:54 org.springframework.test.context.TestContextManager.retrieveTestExecutionListeners(TestContextManager.java:234): Could not instantiate TestExecutionListener class [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their dependencies) available.
测试前置处理
[INFO ] 2017-03-07 00:28:54 org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:316): Loading XML bean definitions from URL [file:/Users/albert/Documents/workspace/AlbertBlog/target/classes/applicationContext.xml]
[INFO ] 2017-03-07 00:28:54 org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:513): Refreshing org.springframework.context.support.GenericApplicationContext@3a7109eb: startup date [Tue Mar 07 00:28:54 CST 2017]; root of context hierarchy
[INFO ] 2017-03-07 00:28:54 org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:172): Loading properties file from URL [file:/Users/albert/Documents/workspace/AlbertBlog/target/classes/application.properties]
[INFO ] 2017-03-07 00:28:55 com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:638): {dataSource-1} inited
Users [uid=1, username=null, password=a66abb5684c45962d887564f08346e8d]
测试后置处理
[INFO ] 2017-03-07 00:28:56 org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:873): Closing org.springframework.context.support.GenericApplicationContext@3a7109eb: startup date [Tue Mar 07 00:28:54 CST 2017]; root of context hierarchy
[INFO ] 2017-03-07 00:28:56 com.alibaba.druid.pool.DruidDataSource.close(DruidDataSource.java:1288): {dataSource-1} closed

Service层测试

/**
 * 
 */
package com.albert.test;

import javax.annotation.Resource;

import org.junit.Test;

import com.albert.TestSupport;
import com.albert.domain.table.Users;
import com.albert.service.UserService;

/** 
* @ClassName: ServiceTest 
* @Description: Service层测试
* @author albert
* @date 2017年3月7日 下午8:58:52 
*  
*/
public class ServiceTest extends TestSupport {
    @Resource
    private UserService service;
    @Test
    public void test(){
        Users users = service.findById(1);
        logger.info("结果:"+users);
    }
}

程序运行后同样打印,结果:Users [uid=1, username=null, password=a66abb5684c45962d887564f08346e8d]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容