美文网首页
Spring + Mybatis + log4j2

Spring + Mybatis + log4j2

作者: 已经是咸鱼的小涛orz | 来源:发表于2017-07-26 17:22 被阅读0次

    Maven

    首先在maven中导入类库

    <!--JSTL JSP标准标签库-->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    
    <!--Spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</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</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-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-orm</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-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <!--servlet-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    
    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    
    <!--mybatis 延迟加载 动态代理工具-->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>${cglib.version}</version>
    </dependency>
    
    <!--mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>
    
    <!--Tomcat-->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
        <version>${tomcat-jdbc.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-pool</groupId>
        <artifactId>commons-pool</artifactId>
        <version>1.1</version>
    </dependency>
    
    <!-- log -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    
    <!--json-->
    <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.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    
    

    配置

    1. Mybatis

    创建Mybatis接口类MyBatisScan

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    @Documented
    @Component
    public @interface MyBatisScan {
        String value() default "";
    }
    

    创建配置文件mybatisConfig.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>
        <settings>
            <!-- 全局映射器启用缓存 -->
            <setting name="cacheEnabled" value="false" />
            <!-- 查询时,关闭关联对象即时加载以提高性能 -->
            <setting name="lazyLoadingEnabled" value="true" />
            <!--开启驼峰式映射-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
            <setting name="multipleResultSetsEnabled" value="true" />
            <!-- 允许使用列标签代替列名 -->
            <setting name="useColumnLabel" value="true" />
            <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
            <setting name="useGeneratedKeys" value="true" />
            <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
            <setting name="autoMappingBehavior" value="FULL" />
            <!-- 对于批量更新操作缓存SQL以提高性能  -->
            <setting name="defaultExecutorType" value="BATCH" />
            <!-- 数据库超过25000秒仍未响应则超时 -->
            <setting name="defaultStatementTimeout" value="25000" />
        </settings>
    </configuration>
    
    1. 数据库

    在resources文件夹中创建属性文件applicationProperties.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/tim?&useUnicode=true&characterEncoding=utf8& zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    jdbc.username=root
    jdbc.password=root
    jdbc.pool.maxIdle=10
    jdbc.pool.maxActive=40
    
      #jdbc properties SQL-Server
      #jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
      #jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=db_name
      #jdbc.username=sa
      #jdbc.password=1q2w3e4r
      #jdbc.pool.maxIdle=10
      #jdbc.pool.maxActive=40
    
    1. Spring

    在resources文件夹中创建配置文件applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:context="http://www.springframework.org/schema/context"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
       <description>Spring公共配置</description>
    
       <!-- 启用spring mvc 注解 -->
       <context:annotation-config />
       <!-- 设置使用注解的类所在的jar包 过滤web层的controller注解-->
       <context:component-scan base-package="com.xtao.tim">
           <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
           <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
       </context:component-scan>
    
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <property name="dataSource" ref="dataSource"/>
           <property name="configLocation" value="classpath:/mybatisConfig.xml"/>
           <property name="mapperLocations" value="classpath*:com/xtao/tim/**/dao/*.xml"/>
       </bean>
    
       <!--mybatis mapper接口查找器-->
       <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
           <property name="basePackage" value="com.xtao.tim"/>
           <property name="annotationClass" value="com.xtao.tim.mybatis.MyBatisScan"/>
           <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       </bean>
    
       <context:property-placeholder ignore-resource-not-found="true" location="classpath*:/applicationProperties.properties"/>
       <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
           <property name="driverClassName" value="${jdbc.driver}"/>
           <property name="url" value="${jdbc.url}"/>
           <property name="username" value="${jdbc.username}"/>
           <property name="password" value="${jdbc.password}"/>
           <property name="maxActive" value="${jdbc.pool.maxActive}"/>
           <property name="maxIdle" value="${jdbc.pool.maxIdle}"/>
           <property name="defaultAutoCommit" value="true"/>
           <property name="testOnBorrow" value="true"/>
           <property name="testOnReturn" value="false"/>
           <property name="testWhileIdle" value="true"/>
           <property name="validationQuery" value="select 1"/>
           <property name="removeAbandonedTimeout" value="600"/>
           <property name="removeAbandoned" value="true"/>
           <property name="timeBetweenEvictionRunsMillis" value="30000"/>
           <property name="minEvictableIdleTimeMillis" value="30000"/>
       </bean>
    </beans>
    
    1. Servlet

    在webapp/WEB-INF下创建project-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <!--扫描@Controller-->
        <context:component-scan base-package="com.xtao.tim">
            <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!--定义spring 视图解析器-->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
            <property name="mediaTypes">
                <value>
                    json=application/json
                    xml=application/xml
                </value>
            </property>
        </bean>
    
        <!--自动扫描spring mvc注解-->
        <mvc:annotation-driven/>
    
        <!-- 容器默认的DefaultServletHandler处理 所有静态内容与无RequestMapping处理的URL-->
        <mvc:default-servlet-handler/>
    
        <!-- 定义无需Controller的url<->view直接映射 -->
        <!--    <mvc:view-controller path="/" view-name="index"/>-->
    
        <context:property-placeholder ignore-resource-not-found="true" location="classpath*:/applicationProperties.properties"/>
    </beans>
    
    1. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             version="3.0">
    
        <display-name>TIM</display-name>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/applicationContext.xml</param-value>
        </context-param>
        <context-param>
            <param-name>log4jConfiguration</param-name>
            <param-value>classpath:/log4j2.xml</param-value>
        </context-param>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!--spring 视图分配器-->
        <servlet>
            <servlet-name>tim</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>tim</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!--
        <welcome-file-list>
                <welcome-file>index</welcome-file>
            </welcome-file-list
                <error-page>
                <error-code>404</error-code>
                <location>/WEB-INF/jsp/error/404.jsp</location>
            </error-page>
            <error-page>
                <error-code>500</error-code>
                <location>/WEB-INF/jsp/error/500.jsp</location>
            </error-page>
            >-->
    
        <session-config>
            <session-timeout>30</session-timeout>
        </session-config>
    </web-app>
    
    1. log4j2

    <?xml version="1.0" encoding="UTF-8"?>
    <!--FF 表示不记录log4j2本身的日志-->
    <configuration status="OFF">
        <properties>
            <property name="LOG_HOME">D:\usr\front\log</property>
            <property name="FILE_NAME">TIM</property>
        </properties>
        <appenders>
            <Console name="Console" target="SYSTEM_OUT">
                <!--#这ThresholdFilter是个类似拦截器 level 填写日志显示类型-->
                <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
                <!--这个都知道是输出日志的格式-->
                <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
            </Console>
    
            <File name="Error" fileName="${LOG_HOME}/error.log">
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            </File>
    
            <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFile" fileName="${LOG_HOME}/${FILE_NAME}.log"
                         filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{MM-dd-yyyy}-%i.log.gz">
                <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
                <!--#日志文件最大值 第二天压缩-->
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="10 MB"/>
                </Policies>
                <!-- 日志文件大小 -->
                <SizeBasedTriggeringPolicy size="20MB" />
                <!-- 最多保留文件数 -->
                <DefaultRolloverStrategy max="20"/>
            </RollingFile>
        </appenders>
        <!--#root 默认加载-->
        <loggers>
            <root level="info">
                <appender-ref ref="RollingFile"/>
                <appender-ref ref="Console"/>
                <appender-ref ref="Error" />
            </root>
        </loggers>
    </configuration>
    

    相关文章

      网友评论

          本文标题:Spring + Mybatis + log4j2

          本文链接:https://www.haomeiwen.com/subject/lmpnkxtx.html