Spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架。

###** SpringMVC** Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

###** MyBatis** MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

开发环境搭建

  • jdk1.7及以上
  • apache-maven-3.3.9
  • apache-tomcat-8.0.9
  • 开发工具IDEA

整合SSM框架

  1. 新建maven工程,目录如下:

springframework和maven版本_测试

  1. 建立MVC分层

springframework和maven版本_java_02

3.resources文件夹下创建资源文件

springframework和maven版本_spring_03

详细配置

1.Maven引入需要的JAR包

jar包用途注释有说明

<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.test</groupId>
  <artifactId>ssmDemo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>ssmDemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.3.6.RELEASE</spring.version>
  </properties>

  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>


    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-dao</artifactId>
      <version>2.0.8</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>

    <!-- druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.26</version>
    </dependency>

    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- log4j日志文件管理 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>


  </dependencies>
  <build>
    <finalName>ssmDemo</finalName>
    <!--这里进行配置,后会自动的加载mapper.xml文件 :配置Maven 对resource文件 过滤 -->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>

    <!--将编译器的版本设定为1.7 -->
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <!-- 基于Maven: MyBatis Generator -->
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
          <verbose>true</verbose>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

2.web.xml配置

<?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"
         id="WebApp_ID" version="2.5">

  <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>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

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

  <servlet>
    <servlet-name>ssmDemo</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>ssmDemo</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>


  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>ssmDemo.root</param-value>
  </context-param>

  <!-- Log4j 配置 -->
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>10000</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

</web-app>

3.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-mvc.xml" />
    <import resource="spring-mybatis.xml"/>

</beans>

4.dataSource.properties配置

driverClassName=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

#<!-- 初始化连接大小 -->
initialSize=0
#<!-- 连接池最大使用连接数量 -->
maxActive=20
#<!-- 连接池最小空闲 -->
minIdle=0
#<!-- 获取连接最大等待时间 -->
maxWait=60000
#<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
minEvictableIdleTimeMillis=25200000
# <!-- 连接超时被回收 -->
removeAbandonedTimeout=1800

5.log4j.properties配置

log4j.rootLogger=info , stdout, D, E

log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG

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{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.D = org.apache.log4j.RollingFileAppender
#指定debug.log文件输出地
log4j.appender.D.File = ${YHHSMS.root}/WEB-INF/logs/debug.log
#指定每个log.debug文件大小为20k,建议设置成20M
log4j.appender.D.MaxFileSize = 20MB
#备份log文件最多为10个,即debug.log10,之后还需要记录日志的话,将重新覆盖debug.log,debug.log.1 ...
log4j.appender.D.MaxBackupIndex=10
#true意思:将消息增加到指定文件中,false指将消息覆盖指定的文件内容
log4j.appender.D.Append = true
#消息输出层次
log4j.appender.D.Threshold = DEBUG
#消息输出样式
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.E = org.apache.log4j.DailyRollingFileAppender
#指定debug.log文件输出地
log4j.appender.E.File = ${YHHSMS.root}/WEB-INF/logs/error.log
#每天产生一个新的日志
log4j.appender.E.DatePattern = "."yyyy-MM-dd
#true意思:将消息增加到指定文件中,false指将消息覆盖指定的文件内容
log4j.appender.E.Append = true
#消息输出层次
log4j.appender.E.Threshold = ERROR
#消息输出样式
log4j.appender.E.layout = org.apache.log4j.PatternLayout
#消息输出格式
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

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


    <!-- driven -->
    <mvc:annotation-driven/>

    <!-- data config -->
    <context:property-placeholder location="classpath:dataSource.properties"/>

    <!-- scan -->
    <context:component-scan base-package="com.test.ssmDemo"/>


</beans>

7.spring-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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.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-4.1.xsd">

    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">

        <property name="url" value="${jdbc.connectionURL}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 连接超时被回收 -->
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/test/ssmDemo/mapper/*.xml" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.ssmDemo.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>


    <!-- 配置事务管理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 使用tx标签配置的拦截器 实现事务注入 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="register*" propagation="REQUIRED" />
            <tx:method name="upd*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut"
                      expression="execution(* com.test.ssmDemo.service.impl.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
                     advice-ref="transactionAdvice" />
    </aop:config>



</beans>

8.generator.properties和generatorConfig.xml配置

PS:基于Maven的Mybatis_generator生成mapper,model 自行百度

关于插件方式生成mapper,model请参考

数据库设计

springframework和maven版本_spring_04

编码设计

实现简单的用户列表查询

1.Controller

package com.test.ssmDemo.controller;

import com.test.ssmDemo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UserController {
  @Autowired
  private UserService userService;

  public static final Logger logger;

  static {
    logger = LoggerFactory.getLogger(UserController.class);
  }

  @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
  public void getUserList() {
    logger.info(userService.getUserList().toString());
  }
}

2.Service

package com.test.ssmDemo.controller;

import com.test.ssmDemo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UserController {
  @Autowired
  private UserService userService;

  public static final Logger logger;

  static {
    logger = LoggerFactory.getLogger(UserController.class);
  }

  @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
  public void getUserList() {
    logger.info(userService.getUserList().toString());
  }
}

3.ServiceImpl

package com.test.ssmDemo.service.impl;

import com.test.ssmDemo.mapper.UserMapper;
import com.test.ssmDemo.model.User;
import com.test.ssmDemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserMapper userMapper;

  @Override
  public List<User> getUserList() {
    return userMapper.selectUserList();
  }
}

4.UserMapper.java

package com.test.ssmDemo.mapper;

import com.test.ssmDemo.model.User;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(String userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(String userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> selectUserList();
}

5.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.test.ssmDemo.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.test.ssmDemo.model.User">
        <id column="user_id" property="userId" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
        <result column="tel" property="tel" jdbcType="VARCHAR"/>
    </resultMap>
    <sql id="Base_Column_List">
    user_id, name, age, tel
  </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
        select
        <include refid="Base_Column_List"/>
        from user
        where user_id = #{userId,jdbcType=VARCHAR}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from user
    where user_id = #{userId,jdbcType=VARCHAR}
  </delete>
    <insert id="insert" parameterType="com.test.ssmDemo.model.User">
    insert into user (user_id, name, age, 
      tel)
    values (#{userId,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{tel,jdbcType=VARCHAR})
  </insert>
    <insert id="insertSelective" parameterType="com.test.ssmDemo.model.User">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                user_id,
            </if>
            <if test="name != null">
                name,
            </if>
            <if test="age != null">
                age,
            </if>
            <if test="tel != null">
                tel,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                #{userId,jdbcType=VARCHAR},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
            <if test="tel != null">
                #{tel,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.test.ssmDemo.model.User">
        update user
        <set>
            <if test="name != null">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
            <if test="tel != null">
                tel = #{tel,jdbcType=VARCHAR},
            </if>
        </set>
        where user_id = #{userId,jdbcType=VARCHAR}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.test.ssmDemo.model.User">
    update user
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      tel = #{tel,jdbcType=VARCHAR}
    where user_id = #{userId,jdbcType=VARCHAR}
  </update>

    <select id="selectUserList" resultType="com.test.ssmDemo.model.User">
    SELECT
  user_id AS userId,
  name,
  age,
  tel
FROM user;
  </select>
</mapper>

最后把项目跑起来

效果如图:

springframework和maven版本_数据库_05