idea中springmvc, mybatis, gradle环境搭建

xiaoxiao2021-02-28  107

Spring mvc和mybatis框架配置总结

开发环境:

Jdk: 1.8

开发IDE:IntelliJ IDEA 2016.3(64)

数据库:mysql 5.7

 

配置文件:

资源文件目录:

1.      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"xmlns:web="http://java.sun.com/xml/ns/javaee"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    id="WebApp_ID"version="3.0">       <!-- ********************************log4j配置**********************************************************-->    <context-param>       <param-name>log4jConfigLocation</param-name>       <param-value>classpath:/log4j.properties</param-value>    </context-param>    <context-param>       <param-name>log4jRefreshInterval</param-name>       <param-value>600000</param-value>    </context-param>       <listener>       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    </listener>       <!-- *****************************************spring配置**********************************************-->       <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:/spring-config.xml</param-value>    </context-param>    <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>                   <!-- *****************************************过滤器************************************************-->       <!-- ****************防止中文乱码******************************-à       <filter>       <filter-name>CharacterEncodingFilter</filter-name>       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>       <async-supported>true</async-supported>       <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> <!-- *******************************将请求及返回结果显示到控制台***********-à    <filter>       <filter-name>requestLogFilter</filter-name>       <filter-class>com.wit.stock.filter.RequestLogFilter</filter-class>       <async-supported>true</async-supported>    </filter>    <filter-mapping>       <filter-name>requestLogFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping> <!--***********************shiro安全配置***********************************à    <filter>       <filter-name>shiroFilter</filter-name>       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>       <init-param>          <param-name>targetFilterLifecycle</param-name>          <param-value>true</param-value>       </init-param>    </filter>       <!-- Make sure any request you want accessible toShiro is filtered. /* catches all -->    <!-- requests.  Usually this filter mapping is defined first(before all others) to -->    <!-- ensure that Shiro works insubsequent filters in the filter chain:             -->    <filter-mapping>       <filter-name>shiroFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping> <!--*******************************************springMVC*******************************************************-->    <servlet>       <servlet-name>mvc-dispatcher</servlet-name>       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:spring-mvc-config.xml</param-value>       </init-param>       <load-on-startup>1</load-on-startup>       <async-supported>true</async-supported>    </servlet>    <servlet-mapping>       <servlet-name>mvc-dispatcher</servlet-name>       <url-pattern>/</url-pattern>    </servlet-mapping> </web-app>

 

 

2.spring mvc 配置:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    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-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/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd         ">    <!-- 对mvc注解支持 -->    <mvc:annotation-driven  >         <mvc:argument-resolvers>             <bean class="com.wit.stock.bind.CurrentUserMethodArgumentResolver"/>         <bean class="com.wit.stock.bind.RequestPageInfoMethodArgumentResolver" />         </mvc:argument-resolvers>    </mvc:annotation-driven>    <bean class="com.wit.stock.document.MySwaggerConfig"/>    <!-- 只扫描@controller注解 -->     <context:component-scan base-package="com.wit.stock.controller">         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />         <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" />         <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>         <context:include-filter type="annotation" expression="org.apache.shiro.authz.annotation.RequiresUser" />     </context:component-scan>    <context:annotation-config/>    <!--<mvc:view-controller path="/" view-name="forward:/index" />-->    <mvc:view-controller path="/" view-name="forward:/signin"/>    <mvc:default-servlet-handler />    <!-- 静态资源映射 -->    <mvc:resources mapping="/assets/images/**" location="/WEB-INF/assets/images/" />    <mvc:resources mapping="/assets/images/gallery/**" location="/WEB-INF/assets/images/gallery/" />    <mvc:resources mapping="/assets/css/**" location="/WEB-INF/assets/css/" />    <mvc:resources mapping="/assets/js/**" location="/WEB-INF/assets/js/" />    <mvc:resources mapping="/assets/font/**" location="/WEB-INF/assets/font/" />    <mvc:resources mapping="/assets/fonts/**" location="/WEB-INF/assets/fonts/" />    <mvc:resources mapping="/assets/avatars/**" location="/WEB-INF/assets/avatars/" />    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>    <mvc:resources mapping="*.html" location="/WEB-INF/"/>    <!-- 定义视图解析器 -->    <bean       class="org.springframework.web.servlet.view.InternalResourceViewResolver">       <property name="prefix" value="/WEB-INF/"/>       <property name="suffix" value=".html"/>    </bean>        <import resource="spring-mvc-shiro.xml"/> </beans>

 

3.spring配置:

<?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:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="         http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-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/aop         http://www.springframework.org/schema/aop/spring-aop-4.1.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-4.1.xsd         ">    <!--<context:annotation-config/>-->    <!-- 读取配置文件 -->    <context:property-placeholder       location="classpath:jdbc-mysql.properties,classpath:tomcat-pool-config.properties,classpath:mail-config.properties" />    <!-- 扫描注解,除去web层注解,web层注解在mvc配置中扫描 -->    <context:component-scan       base-package="com.wit.stock.compoment,com.wit.stock.mapper,com.wit.stock.service">       <context:exclude-filter type="annotation"          expression="org.springframework.stereotype.Controller" />       <context:exclude-filter type="annotation"          expression="org.springframework.web.bind.annotation.RestController" />    </context:component-scan>    <!-- 开启AOP监听 只对当前配置文件有效 -->    <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />    <!-- c3p0连接池 -->    <!-- <import resource="spring-c3p0.xml" /> -->    <!-- tomcat连接池 -->    <import resource="spring-tomcat-pool.xml" />    <!-- hibernate及事物配置 -->    <!-- <import resource="spring-hibernate.xml" /> -->       <import resource="spring-mybatis.xml" />    <!-- 配置邮箱服务器 -->    <import resource="spring-mail.xml" />       <!-- shiro安全模块定义 -->    <import resource="spring-shiro.xml" />    <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 -->    <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->    <tx:annotation-driven transaction-manager="transactionManager"  /> <!--   <bean id="taskExecutor"       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">       <property name="corePoolSize" value="10" />       <property name="maxPoolSize" value="30" />    </bean>-->    <!-- 上传解析 -->    <bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       <property name="maxUploadSize" value="3000000" />    </bean>    <!-- 配置事务异常封装 --> <!--   <bean id="persistenceExceptionTranslationPostProcessor"       class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />--> </beans>

 

4.log4j.properties配置:

#console log log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c(%L) - %m%n #all log log4j.appender.DAILY_ALL=org.apache.log4j.DailyRollingFileAppender log4j.appender.DAILY_ALL.layout=org.apache.log4j.PatternLayout log4j.appender.DAILY_ALL.layout.ConversionPattern="%p %d{yyyy-MM-dd HH:mm:ss} %-50.50c(%L) - %m%n #logger #log4j.logger.org.springframework=TRACE #log4j.logger.org.hibernate=INFO,CONSOLE #log4j.logger.org.apache=INFO,CONSOLE # 配置打印本项目所有log,包括mybati的sql语句 log4j.logger.com.wit.stock=TRACE log4j.rootLogger=INFO,CONSOLE

 

5.tomcat-pool-confin.properties(tomcat连接池配置)

jmxEnabled=true validationInterval=30000 timeBetweenEvictionRunsMillis=30000 maxActive=20 initialSize=3 maxWait=10000 maxIdle=15 removeAbandonedTimeout=60 minEvictableIdleTimeMillis=30000 minIdle=5 logAbandoned=true removeAbandoned=true jdbcInterceptors=org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer validationQuery=SELECT 1 testOnBorrow=true testOnReturn=true testWhileIdle=true

 

 

6.spring-tomcat-pool.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-4.2.xsd         ">     <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"           destroy-method="close">         <property name="poolProperties">             <bean class="org.apache.tomcat.jdbc.pool.PoolProperties">                 <property name="url" value="${jdbc.url}"/>                 <property name="driverClassName" value="${jdbc.driverClassName}"/>                 <property name="username" value="${jdbc.user}"/>                 <property name="password" value="${jdbc.pass}"/>                 <property name="jmxEnabled" value="${jmxEnabled}"/>                 <property name="validationInterval" value="${validationInterval}"/>                 <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>                 <property name="maxActive" value="${maxActive}"/>                 <property name="initialSize" value="${initialSize}"/>                 <property name="maxWait" value="${maxWait}"/>                 <property name="maxIdle" value="${maxIdle}"/>                 <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>                 <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>                 <property name="minIdle" value="${minIdle}"/>                 <property name="logAbandoned" value="${logAbandoned}"/>                 <property name="removeAbandoned" value="${removeAbandoned}"/>                 <property name="jdbcInterceptors" value="${jdbcInterceptors}"/>                 <property name="validationQuery" value="${validationQuery}"/>                 <property name="testOnBorrow" value="${testOnBorrow}"/>                 <property name="testOnReturn" value="${testOnReturn}"/>                 <property name="testWhileIdle" value="${testWhileIdle}"/>             </bean>         </property>     </bean> </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/beans             http://www.springframework.org/schema/beans/spring-beans-4.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.1.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-4.1.xsd         ">    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource"/>       <property name="mapperLocations">          <list>             <value>classpath:mybatis_mapper/*.xml</value>          </list>       </property>       <property name="typeAliasesPackage" value="com.wit.stock.model"/>       <property name="plugins">          <list>             <bean class="com.github.pagehelper.PageHelper">                <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->                <property name="properties">                   <value>                      dialect=mysql                      reasonable=true                      supportMethodsArguments=true                      returnPageInfo=check                      params=count=countSql                   </value>                </property>             </bean>          </list>       </property>    </bean>    <bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource2"/>       <property name="mapperLocations">          <list>             <value>classpath:mybatis_mapper/*.xml</value>          </list>       </property>       <property name="typeAliasesPackage" value="com.wit.stock.model"/>       <property name="plugins">          <list>             <bean class="com.github.pagehelper.PageHelper">                <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->                <property name="properties">                   <value>                      dialect=mysql                      reasonable=true                      supportMethodsArguments=true                      returnPageInfo=check                      params=count=countSql                   </value>                </property>             </bean>          </list>       </property>    </bean>    <bean id="sqlSessionFactory3" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource3"/>       <property name="mapperLocations">          <list>             <value>classpath:mybatis_mapper/*.xml</value>          </list>       </property>       <property name="typeAliasesPackage" value="com.wit.stock.model"/>       <property name="plugins">          <list>             <bean class="com.github.pagehelper.PageHelper">                <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->                <property name="properties">                   <value>                      dialect=mysql                      reasonable=true                      supportMethodsArguments=true                      returnPageInfo=check                      params=count=countSql                   </value>                </property>             </bean>          </list>       </property>    </bean> <!—mybatis数据库基本操作插件配置—>    <bean id="msc1" class="tk.mybatis.spring.mapper.MapperScannerConfigurer">       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>       <property name="basePackage" value="com.wit.stock.mapper"/>       <!-- 3.2.2版本新特性,markerInterface可以起到mappers配置的作用,详细情况需要看Marker接口类 -->       <!-- <property name="markerInterface" value="com.isea533.mybatis.util.MyMapper"/>-->       <!-- 通用Mapper通过属性注入进行配置,默认不配置时会注册Mapper<T>接口 -->       <!--<property name="properties">             <value>                 mappers=tk.mybatis.mapper.common.Mapper             </value>         </property>-->    </bean>    <bean id="msc2" class="tk.mybatis.spring.mapper.MapperScannerConfigurer">       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"></property>       <property name="basePackage" value="com.wit.stock.mapper2"/>       <!-- 3.2.2版本新特性,markerInterface可以起到mappers配置的作用,详细情况需要看Marker接口类 -->       <!-- <property name="markerInterface" value="com.isea533.mybatis.util.MyMapper"/>-->       <!-- 通用Mapper通过属性注入进行配置,默认不配置时会注册Mapper<T>接口 -->       <!--<property name="properties">             <value>                 mappers=tk.mybatis.mapper.common.Mapper             </value>         </property>-->    </bean>    <bean id="msc3" class="tk.mybatis.spring.mapper.MapperScannerConfigurer">       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory3"></property>       <property name="basePackage" value="com.wit.stock.mapper3"/>       <!-- 3.2.2版本新特性,markerInterface可以起到mappers配置的作用,详细情况需要看Marker接口类 -->       <!-- <property name="markerInterface" value="com.isea533.mybatis.util.MyMapper"/>-->       <!-- 通用Mapper通过属性注入进行配置,默认不配置时会注册Mapper<T>接口 -->       <!--<property name="properties">             <value>                 mappers=tk.mybatis.mapper.common.Mapper             </value>         </property>-->    </bean>    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"       scope="prototype">       <constructor-arg index="0" ref="sqlSessionFactory" />    </bean> <!—spring mvc数据库事务配置—>    <aop:aspectj-autoproxy />    <aop:config>       <aop:pointcut id="appService"          expression="execution(* com.wit.stock.service..*Service*.*(..))" />       <aop:advisor advice-ref="txAdvice" pointcut-ref="appService" />    </aop:config>    <tx:advice id="txAdvice" transaction-manager="transactionManager">       <tx:attributes>          <tx:method name="select*" read-only="true" />          <tx:method name="find*" read-only="true" />          <tx:method name="get*" read-only="true" />          <tx:method name="sava*" />       </tx:attributes>    </tx:advice>    <bean id="transactionManager"       class="org.springframework.jdbc.datasource.DataSourceTransactionManager">       <property name="dataSource" ref="dataSource" />    </bean> </beans>

 

8.spring-mvc-shiro.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:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="         http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-4.2.xsd            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.1.xsd         ">    <aop:config proxy-target-class="true" />    <bean       class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"       depends-on="lifecycleBeanPostProcessor">       <!--<property name="proxyTargetClass" value="true" />-->    </bean>    <bean       class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">       <property name="securityManager" ref="securityManager" />    </bean> </beans>        

 

9.请求过滤器定义:

AbstractFilter.java

 

package com.wit.stock.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public abstract class AbstractFilter implements Filter {    @Override    public void doFilter(ServletRequest req, ServletResponse res,          FilterChain chain) throws IOException, ServletException {       HttpServletRequest request = (HttpServletRequest) req;       HttpServletResponse response = (HttpServletResponse) res;       HttpSession session = request.getSession(false);       String menthod = request.getMethod();       String requestUri = request.getRequestURI();       String contextPath = request.getContextPath();       String url = requestUri.substring(contextPath.length());             /*    System.out.println("requestUri: " + requestUri);       System.out.println("contextPath: " + contextPath);       System.out.println("url: " + url);*/             doFilter(request, response, chain, session, menthod, url);    }    /**     *     * @param request     *            request     * @param response     *            response     * @param session     *            session 可能为空     * @param menthod     *            menthod     * @param url     *            url     */    public abstract void doFilter(HttpServletRequest request,          HttpServletResponse response, FilterChain chain,          HttpSession session, String menthod, String url)          throws IOException, ServletException; }

 

RequestLogFilter.java

package com.wit.stock.filter; import java.io.IOException; import java.util.Map; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RequestLogFilter extends AbstractFilter {    private static Logger logger=null;    public void init(FilterConfig config) {       logger = LoggerFactory.getLogger(RequestLogFilter.class);    }    public void destroy() {       logger = null;    }    public static String getParamsString(Map<String, String[]> params) {       if (params == null || params.isEmpty())          return "";       StringBuilder builder = new StringBuilder();       builder.append("?");             for (String key : params.keySet()) {          builder.append(key).append("=").append(params.get(key)[0])                .append("&");       }       builder.deleteCharAt(builder.lastIndexOf("&"));       return builder.toString();    }    @Override    public void doFilter(HttpServletRequest request,          HttpServletResponse response, FilterChain chain,          HttpSession session, String menthod, String url)          throws IOException, ServletException {       logger.info("Accept:{}",request.getHeader("Accept"));       logger.info("Content-Type:{}",request.getHeader("Content-Type"));       logger.info("------开始过滤--------");       long before = System.currentTimeMillis();       logger.info("拦截到请求:{} : {}{}", menthod,url,getParamsString(request.getParameterMap()));       chain.doFilter(request, response);       long after = System.currentTimeMillis();       logger.info("请求结果:" + url + " status:" + response.getStatus());       logger.info("花费时间:" + (after - before) + "ms");             logger.info("------过滤结束---------\n");    } }

 

10.gradle配置:

version '2.0' apply plugin: 'war' apply plugin: 'idea' apply plugin: 'eclipse-wtp' apply plugin: 'org.akhikhl.gretty' apply plugin: 'org.flywaydb.flyway' apply plugin: 'io.github.robwin.swagger2markup' apply plugin: 'org.asciidoctor.convert' //指定gradle wrapper版本 task wrapper(type: Wrapper) {     gradleVersion = '2.3' } configurations {     mybatisGenerator } //配置插件仓库 buildscript {     repositories {         mavenCentral()         jcenter()     }     dependencies {         classpath 'org.akhikhl.gretty:gretty:1.2.4'         classpath: 'mysql:mysql-connector-java:5.1.36'         classpath "org.flywaydb:flyway-gradle-plugin:4.0"         //swagger2markup         classpath 'io.github.robwin:swagger2markup-gradle-plugin:0.9.2'         classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'         classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'         classpath 'io.github.robwin:swagger2markup-gradle-plugin:0.9.2'     } } //gretty设置 gretty {     port = 8080     contextPath = "/" } ext {     if (!project.hasProperty("env")) {         println '没有配置数据环境,默认使用 开发环境'         env = "dev"     }     println "使用数据库环境为:${project['env']}"     asciiDocOutputDir = file("${buildDir}/asciidoc")     println asciiDocOutputDir.absolutePath     swaggerOutputDir = file("${buildDir}/swagger")     println swaggerOutputDir.absolutePath } def getDbProperties = {     def properties = new Properties()     def dbPropertiesPath = sourceSets.main.resources.srcDirs[1].path;     file("$dbPropertiesPath/jdbc-mysql.properties").withInputStream { inputStream ->         properties.load(inputStream)     }     properties; } sourceSets {     main {         resources {             srcDir("src/main/resources")             if (project['env'] == 'dev') {                 srcDir("src/main/resources-dev")             } else if (project['env'] == 'prod') {                 srcDir('src/main/resources-prod')             }         }     } } test {     systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir } convertSwagger2markup {     dependsOn clean,test     inputDir swaggerOutputDir     examplesDir asciiDocOutputDir     pathsGroupedBy io.github.robwin.swagger2markup.GroupBy.TAGS } asciidoctor {     dependsOn convertSwagger2markup     sources {         include 'index.adoc'     }     backends = ['html5', 'pdf']     attributes = [             doctype: 'book',             'source-highlighter': 'coderay',             toc: 'left',             toclevels: '3',             numbered: '',             sectlinks: '',             sectanchors: '',             hardbreaks: '',             generated: asciiDocOutputDir     ] } flyway {     def prop = getDbProperties()     user = prop.getProperty('jdbc.user')     url = prop.getProperty('jdbc.url')     password = prop.getProperty('jdbc.pass')     locations = ["filesystem:db/migration"] } repositories {     mavenCentral()     maven {         url 'https://repo.spring.io/libs-milestone'     } } //统一编码为utf-8 [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' //依赖 dependencies {     testCompile 'com.jayway.restassured:rest-assured:2.9.0'     testCompile group: 'junit', name: 'junit', version: '4.12'     testCompile 'org.springframework:spring-test:4.2.5.RELEASE'     testCompile 'org.hamcrest:hamcrest-core:1.3'     testCompile 'org.mockito:mockito-core:1.10.19'     testCompile 'com.jayway.restassured:json-schema-validator:2.9.0'     testCompile 'com.jayway.restassured:spring-mock-mvc:2.9.0'     testCompile "org.springframework.restdocs:spring-restdocs-restassured:1.1.0.RC1"     //maven仓库中心没有的jar,则放入libs目录下     compile fileTree(dir: 'libs', include: ['*.jar'])     compile 'org.springframework:spring-webmvc:4.2.5.RELEASE'     compile 'org.springframework:spring-orm:4.2.5.RELEASE'     compile 'org.springframework:spring-context-support:4.2.5.RELEASE'     compile 'mysql:mysql-connector-java:5.1.38'     compile 'org.mybatis:mybatis:3.4.0'     compile 'org.mybatis:mybatis-spring:1.3.0'     compile 'com.github.pagehelper:pagehelper:4.1.3'     compile 'org.apache.shiro:shiro-spring:1.2.4'     compile 'org.apache.shiro:shiro-web:1.2.4'     compile 'org.apache.tomcat:tomcat-jdbc:8.0.33'     compile 'javax.mail:mail:1.4.7'     compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'     compile 'org.aspectj:aspectjweaver:1.8.9'     compile 'commons-fileupload:commons-fileupload:1.3.1'     compile 'org.slf4j:slf4j-log4j12:1.7.21'     compile 'tk.mybatis:mapper:3.3.8'     providedCompile 'javax.servlet:javax.servlet-api:3.1.0'     compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.7.3'     //swagger     compile "io.springfox:springfox-swagger2:2.4.0"     compile 'io.springfox:springfox-swagger-ui:2.4.0'     compile 'io.springfox:springfox-staticdocs:2.4.0'     testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc:1.1.0.RC1'     compile 'io.github.robwin:assertj-swagger:0.1.2'     testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.4.0'     mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.2'     mybatisGenerator 'mysql:mysql-connector-java:5.1.38'     mybatisGenerator 'tk.mybatis:mapper:3.3.8' } task mybatisGenerate << {     def prop = getDbProperties()     ant.properties['targetProject'] = projectDir.path     ant.properties['driverClass'] = prop.getProperty('jdbc.driverClassName')     ant.properties['connectionURL'] = prop.getProperty('jdbc.url')     ant.properties['userId'] = prop.getProperty('jdbc.user')     ant.properties['password'] = prop.getProperty('jdbc.pass')     ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path     ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path     ant.properties['modelPackage'] = this.modelPackage     ant.properties['mapperPackage'] = this.mapperPackage     ant.properties['sqlMapperPackage'] = this.sqlMapperPackage     ant.taskdef(             name: 'mbgenerator',             classname: 'org.mybatis.generator.ant.GeneratorAntTask',             classpath: configurations.mybatisGenerator.asPath     )     ant.mbgenerator(overwrite: true,             configfile: 'db/generatorConfig.xml', verbose: true) {         propertyset {             propertyref(name: 'targetProject')             propertyref(name: 'userId')             propertyref(name: 'driverClass')             propertyref(name: 'connectionURL')             propertyref(name: 'password')             propertyref(name: 'src_main_java')             propertyref(name: 'src_main_resources')             propertyref(name: 'modelPackage')             propertyref(name: 'mapperPackage')             propertyref(name: 'sqlMapperPackage')         }     } }

 

11.logback.xml配置(logback和log4j都可以作为spring mvc的日志输出,但logback比log4j更新,使用时选择一种即可):

<!--?xml version="1.0" encoding="UTF-8"?--> <configuration debug="true">     <appender name="console-std" class="ch.qos.logback.core.ConsoleAppender">         <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->         <encoder>             <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>         </encoder>     </appender>     <appender name="file-std" class="ch.qos.logback.core.FileAppender">         <file>c:/ben/ben.log</file>         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">             <fileNamePattern>c:/ben/ben.%d{yyyy-MM-dd}.log</fileNamePattern>             <maxHistory>30</maxHistory>         </rollingPolicy>         <encoder><!-- 必须指定,否则不会往文件输出内容 -->             <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>         </encoder>         <append>true</append>         <prudent>false</prudent>     </appender>     <root level="error">         <appender-ref ref="file-std"/>     </root> </configuration>

 

转载请注明原文地址: https://www.6miu.com/read-64718.html

最新回复(0)