前言

针对于spring的热门,先做一下记录–额,网上现成多得是,很早都在使用,不过最近有个架构用到spring,所以现在来补一补。

具体配置

首先,配置需要用到的第三方类库,提醒:postgresql的jdbc类库千万千万不要用maven上面的那一个,否则会出现 没办法初始化这种奇葩的问题的。

针对我个人的类库,pom 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tmvc2</groupId>
    <artifactId>tmvc2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- 神兽一般的提醒!!!!:不要用maven上面的postgresql驱动,因为是不行的!!!要用官网下载下来的!!! -->
        <!--&lt;!&ndash; https://mvnrepository.com/artifact/postgresql/postgresql &ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>postgresql</groupId>-->
            <!--<artifactId>postgresql</artifactId>-->
            <!--<version>9.1-901-1.jdbc4</version>-->
        <!--</dependency>-->

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- Servlet web -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>compile</scope>
        </dependency>


    </dependencies>



</project>

对了,你要额外引入:
这里写图片描述

从官网下载的postgresql的jdbc驱动。。

项目结构

这里写图片描述

这个是测试配置用项目,我就不那么讲究了,第一层是test,分别有dao—mybatis的mapper接口层,model及vo—沿袭我自己的习惯,不用pojo,model是数据库的记录model,用来编辑及保存数据库表记录的,vo是表现层的数据对象,viewobject,用来显示用得。这两者是有很大不同的,譬如一个用户,数据库里面有region id—地区区域的id,那么对应于vo里面,除了有region id之外,还需要有一个region name给前台进行显示—-总不能让前台自行翻译吧?service是服务层接口,注意,serviceImpl是服务层的具体实现,resource文件夹下面,有conf配置文件夹,下面有dev,test,product三种环境的配置文件,这三种环境很明显一点就是数据库通常都是不一样的,所以大家可以看到三个环境下面都有一份db properties文件在。conf/spring则是spring框架下面的各种配置文件,譬如,db数据库的spring配置,mvc配置,服务层配置等等。mapper文件夹则是所有mybatis的xmlmapper文件。web inf下面的applicationContext配置文件要注意下,因为我个人将其作为优先级最高的配置,也作为spring profile导入不同环境配置的关键入口。

关键配置解释

web xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--配置所有spring相关配置文件,注意,这里先引入applicationContext的配置,然后在将spring下面的配置文件都引入-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml,
            classpath:conf/spring/spring-*.xml</param-value>
    </context-param>

    <!-- 配置spring的profile 注意,这个就是设定profile了,根据profile不一样后续会引入不同的环境配置的,就是说,web xml每次更新都是不能轻易更新的文件,万一开发环境这份文件
     更到正式环境就等着哭吧。
     -->
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>development</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <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:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>


</web-app>

applicationContext.xml解释:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
       <!--利用spring自带的profile切换各个环境的配置。-->
       <!--你需要在web.xml里面指定当前是哪一个环境。这表示web。xml不能随意更新上去-->
       <!-- 开发环境配置文件 -->
       <beans profile="development">
              <context:property-placeholder
                      location="classpath:conf/dev/*.properties" />
       </beans>

       <!-- 测试环境配置文件 -->
       <beans profile="test">
              <context:property-placeholder
                      location="classpath:conf/test/*.properties" />
       </beans>

       <!-- 生产环境配置文件 -->
       <beans profile="production">
              <context:property-placeholder
                      location=" classpath:conf/product/*.properties" />
       </beans>
       <!--利用spring自带的profile切换各个环境的配置。end-->


</beans>

spring-db.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:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">




    <context:component-scan base-package="test.dao" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <!-- 数据库基本信息配置 -->
        <property name="url" value="${druid.jdbcUrl}" />

        <property name="username" value="${druid.username}" />
        <property name="password" value="${druid.password}" />
        <property name = "driverClassName" value = "${druid.driverClassName}" />

        <!-- 初始化连接数量 -->
        <property name="initialSize" value="${druid.initialSize}" />
        <!-- 最小空闲连接数 -->
        <property name="minIdle" value="${druid.minIdle}" />
        <!-- 最大并发连接数 -->
        <property name="maxActive" value="${druid.maxActive}" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${druid.maxWait}" />

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

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

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。 -->
        <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
                  value="${druid.maxPoolPreparedStatementPerConnectionSize}" />

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="${druid.filters}" />



    </bean>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/conf/mybatis.xml"/>
        <property name="mapperLocations">
            <list>
                <value>classpath*:mapper/*Mapper.xml</value>
                <value>classpath*:mapper/**/*Mapper.xml</value>
            </list>
        </property>
        <!--<property name="typeAliasesPackage" value="com.mengdee.manager.domain" />-->

    </bean>


    <!-- 配置mybatis mapper接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="test.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
    <!-- 事务配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 使用annotation注解方式配置事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
</beans>

对应的db.properties配置–注意,我就放一个范本,几个环境需要的参数一样,就是数值和ip数据库,账号密码什么的不一样:

druid.driverClassName=org.postgresql.Driver
druid.jdbcUrl = jdbc:postgresql://aa.bbb.ccc.ddd:5432/你自己的数据库
druid.username = 数据库账号
druid.password = 数据库密码
druid.initialSize=10
druid.minIdle=6
druid.maxActive=50
druid.maxWait=60000
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=SELECT 'x'
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
druid.poolPreparedStatements=false
druid.maxPoolPreparedStatementPerConnectionSize=20
druid.filters=wall,stat

spring-mvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!--控制器路由,view层配置 begin-->
    <!-- scan the package and the sub package 配置需要扫描的控制器的package-->
    <context:component-scan base-package="test.SpringMVC"/>
    <!-- don't handle the static resource -->
    <mvc:default-servlet-handler />

    <!-- if you use annotation you must configure following setting -->
    <mvc:annotation-driven />

    <!-- configure the InternalResourceViewResolver 配置引擎及模板所在目录,模板的后缀
    话说我个人感觉 jsp很好用,如果苛求更好的模板体验,应该直接用vuejs或其他前端框架的,别为难后台模板了。-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>



    <!--控制器路由,view层配置 end-->




</beans>

spring-service.xml服务层配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">


    <!--service 服务层 配置 begin-->
    <context:component-scan base-package="test.serviceImpl" >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>



    <!--service 服务层 配置 end-->
</beans>

好了,当然,放个 mybatis.xml的配置出来,其实,这样配置的话,mybatisxml暂时不用配什么的。因为都自动扫描目录了。

<?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>
    <!--<environments default="development">-->
        <!--<environment id="development">-->
            <!--<transactionManager type="JDBC" />-->
            <!--&lt;!&ndash; 配置数据库连接信息 &ndash;&gt;-->
            <!--<dataSource type="POOLED">-->
                <!--<property name="driver" value="com.mysql.jdbc.Driver" />-->
                <!--<property name="url" value="jdbc:mysql://localhost:3306/SSM_XML"/>-->
                <!--<property name="username" value="root" />-->
                <!--<property name="password" value="root" />-->
            <!--</dataSource>-->
        <!--</environment>-->
    <!--</environments>-->
    <!--<mappers>-->
        <!--&lt;!&ndash; 注册userMapper.xml文件,&ndash;&gt;-->
        <!--<mapper resource="mapper/MemberRoleMapper.xml"></mapper>-->
    <!--</mappers>-->
</configuration>

测试

为了测试整个配置能够正常运行,我特意写了demo代码,假定数据库里面有一张表叫做:
member_role的,结构如下:

CREATE TABLE "public"."member_role" (
"uid" int4 NOT NULL,
"role" int2 NOT NULL
)

;

别嫌简单了,测试而已。

分别写对应的:dao,mapper.xmlservice,serviceImpl
例如:

dao

package test.dao;

import org.apache.ibatis.annotations.Param;
import test.vo.MemberRole;

import java.util.ArrayList;
import java.util.List;
public interface MemberRoleMapper {

    //--通用方法
    public ArrayList<MemberRole> simpleSearch();

}

service接口:

import org.springframework.stereotype.Service;
import test.vo.MemberRole;

import java.util.ArrayList;


public interface TMemberService{
    ArrayList<MemberRole> getAllRoles();
}

serviceImpl具体实现:

package test.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import test.dao.MemberRoleMapper;
import test.service.TMemberService;
import test.vo.MemberRole;

import java.util.ArrayList;

@Service("memberService")
public class TMemberServiceImpl  implements TMemberService {
    @Autowired
    private MemberRoleMapper roleMapper;

    public ArrayList<MemberRole> getAllRoles() {
        System.out.println("get all roles");
        ArrayList<MemberRole> roles=roleMapper.simpleSearch();
        System.out.println(JSONObject.toJSONString(roles));
        return null;
    }
}

mapper对应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="test.dao.MemberRoleMapper">

    <select id="simpleSearch" resultType="test.vo.MemberRole">
        select * from member_role;
</select>

</mapper>

对应的vo对象:

package test.vo;

public class MemberRole {

    public   Long  uid=0L;
    public void setUid(Long uid){
        this.uid=uid;
    }
    public Long getUid(){
        return this.uid;
    }
    public   Integer  role=0;
    public void setRole(Integer role){
        this.role=role;
    }
    public Integer getRole(){
        return this.role;
    }


    public void setNULL(){
        this.uid=null;
        this.role=null;
    }

    public void resetDefaultVal(){
        this.uid=0L;
        this.role=0;
    }


}

好了,最后的控制器:

package test.SpringMVC;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import test.service.TMemberService;

@Controller
@RequestMapping("/mvc")
public class mvcController {

    @Autowired
    private TMemberService memberService;
    @RequestMapping("/hello")
    public String hello(){
        memberService.getAllRoles();

        return "hello";
    }
}

结语

这份东西只是基本的spring+mybatis+druid的配置,还有很多很多东西没加进去,不过这个是某个大架构的一个技术点,以后还会用到的,当然,dao vo 服务层这些都可以用工具生成的,没必要那么累。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐