Spring总结--> 第二结 SpringAOP日志

2018-06-27 10:02:06来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 

SpringAOP日志记录一下,代码就贴完整代码,一劳永逸。

SpringAOP面向切面编程,拦截指定代码,对该代码进行增强。

SpringAOP实现日志很简单

  • 第一种方式配置XML文件
    • 在Spring的XML文件中配置拦截
    • 定义增强代码就OK了
    • 运行结果
      •  

         
  • 第二种方式注解
    • 配置Spring.xml文件
      • 1 <!-- 声明自动为spring容器中那些配置@aspectJ切面的bean创建代理 -->
        2 <aop:aspectj-autoproxy proxy-target-class="true" />
    • 定义增强代码
      •  1 package com.xxw.util;
         2 
         3 import org.aspectj.lang.JoinPoint;
         4 import org.aspectj.lang.annotation.After;
         5 import org.aspectj.lang.annotation.Aspect;
         6 import org.aspectj.lang.annotation.Before;
         7 import org.slf4j.Logger;
         8 import org.slf4j.LoggerFactory;
         9 import org.springframework.stereotype.Component;
        10 
        11 import java.text.SimpleDateFormat;
        12 import java.util.Date;
        13 
        14 @Aspect
        15 @Component
        16 public class AnnotationLoggerAspect {
        17 
        18     private final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);
        19 
        20     /**
        21      * 前置信息
        22      * @param joinPoint
        23      * @throws Exception
        24      */
        25     @Before(value = "execution(* com.xxw.controller.*.*(..))")
        26     public void logBefore(JoinPoint joinPoint) throws  Exception{
        27         logger.info(getInformation(joinPoint)+"---- start");
        28     }
        29 
        30     /**
        31      * 后置信息
        32      * @param joinPoint
        33      * @throws Exception
        34      */
        35     @After(value = "execution(* com.xxw.controller.*.*(..))")
        36     public void logAfter(JoinPoint joinPoint) throws  Exception{
        37         logger.info(getInformation(joinPoint)+"---- end");
        38     }
        39 
        40     /**
        41      * 生成描述信息
        42      * @param joinPoint
        43      * @return
        44      * @throws Exception
        45      */
        46     private String getInformation(JoinPoint joinPoint) throws  Exception{
        47         // 获取类名
        48         String targetName = joinPoint.getTarget().getClass().getName();
        49         // 获取方法名
        50         String methodName = joinPoint.getSignature().getName();
        51         // 当前时间
        52         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        53         return sdf.format(new Date())+"----:"+targetName+"."+methodName;
        54     }
        55 
        56 }
    • 运行结果
      •  


         

下面贴完整代码

一、大概项目目录结构

 

二、各种配置文件

  1. jdbc.properties
    1.  1 driver=com.mysql.jdbc.Driver
       2 url=jdbc:mysql://127.0.0.1:3306/company
       3 username=root
       4 password=root
       5 
       6 # 定义初始化连接数
       7 initialSize=0
       8 # 定义最大连接数
       9 maxActive=20
      10 # 定义最大空闲
      11 maxIdle=20
      12 # 定义最小空闲
      13 minIdle=1
      14 # 定义最长等待时间
      15 maxWait=60000
      View Code
  2. log4j.properties
    1.  1 ########################################################################
       2 ## 日志输出到控制台
       3 ########################################################################
       4 #定义LOG输出级别
       5 log4j.rootLogger=DEBUG,Console,File
       6 #定义日志输出目的地为控制台
       7 log4j.appender.Console=org.apache.log4j.ConsoleAppender  
       8 log4j.appender.Console.Target=System.out  
       9 #可以灵活地指定日志输出格式,下面一行是指定具体的格式
      10 log4j.appender.Console.layout = org.apache.log4j.PatternLayout
      11 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
      12 
      13 ########################################################################
      14 ## 日志输出到物理文件
      15 ########################################################################
      16 #文件大小到达指定尺寸的时候产生一个新的文件
      17 log4j.appender.File = org.apache.log4j.RollingFileAppender  
      18 #指定输出目录
      19 log4j.appender.File.File = logs/yyyy-MM-dd.log  
      20 #定义文件最大大小
      21 log4j.appender.File.MaxFileSize = 10MB  
      22 # 输出所有日志,如果换成DEBUG表示输出DEBUG以上级别日志
      23 log4j.appender.File.Threshold = DEBUG  
      24 log4j.appender.File.layout = org.apache.log4j.PatternLayout  
      25 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
      26 ########################################################################
      View Code
  3. applicationContext-DataSource.xml
    1.  1 <?xml version="1.0" encoding="UTF-8"?>
       2 <beans xmlns="http://www.springframework.org/schema/beans"
       3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       4        xmlns:aop="http://www.springframework.org/schema/aop"
       5        xmlns:tx="http://www.springframework.org/schema/tx"
       6        xsi:schemaLocation="http://www.springframework.org/schema/beans
       7         http://www.springframework.org/schema/beans/spring-beans.xsd
       8         http://www.springframework.org/schema/aop
       9         http://www.springframework.org/schema/aop/spring-aop.xsd
      10         http://www.springframework.org/schema/tx
      11         http://www.springframework.org/schema/tx/spring-tx.xsd">
      12 
      13     <!-- 引入JDBC 配置文件 -->
      14     <bean id="propertyConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      15         <property name="location" value="classpath:jdbc.properties" />
      16     </bean>
      17 
      18     <!-- 配置数据源 -->
      19     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
      20         <property name="driverClassName" value="${driver}" />
      21         <property name="url" value="${url}" />
      22         <property name="username" value="${username}" />
      23         <property name="password" value="${password}" />
      24         <property name="initialSize" value="${initialSize}" />
      25         <property name="maxActive" value="${maxActive}" />
      26         <property name="maxIdle" value="${maxIdle}" />
      27         <property name="minIdle" value="${minIdle}" />
      28         <property name="maxWait" value="${maxWait}" />
      29     </bean>
      30 
      31     <!-- 配置mybatis -->
      32     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      33         <property name="dataSource" ref="dataSource" />
      34         <property name="configLocation" value="classpath:mybatis-config.xml" />
      35         <!-- 自动扫描mapping.xml文件 -->
      36         <property name="mapperLocations" value="classpath:com/xxw/mapper/*.xml" />
      37     </bean>
      38 
      39     <!-- sql 会话模板 -->
      40     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" >
      41         <constructor-arg ref="sqlSessionFactory" />
      42     </bean>
      43 
      44     <!-- 事物处理 -->
      45     <aop:config>
      46         <aop:pointcut id="pc" expression="execution(* com.xxw.service..*(..))" />
      47         <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
      48     </aop:config>
      49     <tx:advice id="txAdvice" transaction-manager="transactionManager">
      50         <tx:attributes>
      51             <tx:method name="delete*" propagation="REQUIRED" />
      52             <tx:method name="insert*" propagation="REQUIRED" />
      53             <tx:method name="update*" propagation="REQUIRED" />
      54             <tx:method name="save*" propagation="REQUIRED" />
      55             <tx:method name="*" propagation="SUPPORTS" />
      56         </tx:attributes>
      57     </tx:advice>
      58     <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      59         <property name="dataSource" ref="dataSource" />
      60     </bean>
      61 
      62 </beans>
      View Code
  4. applicationContext-Main.xml
    1.  1 <?xml version="1.0" encoding="UTF-8"?>
       2 <beans xmlns="http://www.springframework.org/schema/beans"
       3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       4        xmlns:context="http://www.springframework.org/schema/context"
       5        xsi:schemaLocation="http://www.springframework.org/schema/beans
       6             http://www.springframework.org/schema/beans/spring-beans.xsd
       7             http://www.springframework.org/schema/context
       8             http://www.springframework.org/schema/context/spring-context.xsd">
       9 
      10     <!-- 启用注解 -->
      11     <context:annotation-config />
      12 
      13     <!-- 启用组件扫描, 排除#controller组件,该组件由ApplicationContext-MVC.xml配置文件扫描 -->
      14     <context:component-scan base-package="com.xxw">
      15         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"  />
      16     </context:component-scan>
      17 
      18     <!-- 引入DataSource配置文件 -->
      19     <import resource="classpath*:applicationContext-DataSource.xml" />
      20 
      21 </beans>
      View Code
  5. applicationContext-MVC.xml
    1.  1 <?xml version="1.0" encoding="UTF-8"?>
       2 <beans xmlns="http://www.springframework.org/schema/beans"
       3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       4        xmlns:context="http://www.springframework.org/schema/context"
       5        xmlns:mvc="http://www.springframework.org/schema/mvc"
       6        xmlns:aop="http://www.springframework.org/schema/aop"
       7        xsi:schemaLocation="http://www.springframework.org/schema/beans
       8             http://www.springframework.org/schema/beans/spring-beans.xsd
       9             http://www.springframework.org/schema/context
      10             http://www.springframework.org/schema/context/spring-context.xsd
      11             http://www.springframework.org/schema/mvc
      12             http://www.springframework.org/schema/mvc/spring-mvc.xsd
      13             http://www.springframework.org/schema/aop
      14             http://www.springframework.org/schema/aop/spring-aop.xsd">
      15 
      16     <!-- 使用注解开发, 自动扫描包 -->
      17     <context:component-scan base-package="com.xxw.controller" />
      18     <!-- Spring MVC 为 @Controller分发请求所必需的 -->
      19     <mvc:annotation-driven />
      20     <!-- 静态资源访问 (交由DispatcherServlet 来处理静态资源访问) -->
      21     <mvc:default-servlet-handler />
      22     <!-- 更智能的静态访问(js/image)的访问(有SpringMVC自己来处理静态资源访问) -->
      23     <mvc:resources mapping="/static/js/**/" location="/static/js/**" />
      24     <mvc:resources mapping="/static/image/**/" location="/static/image/**" />
      25 
      26     <!-- 设置proxy-target-class属性为true,基于cglib动态代理(Spring的代理)
      27          设置proxy-target-class属性为false,基于JavaSE代理(JDK的动态代理)
      28      -->
      29     <aop:config proxy-target-class="true" />
      30     <!-- 注入自定义日志类 -->
      31     <bean id="logAspect" class="com.xxw.util.LoggerAspect" />
      32     <!-- 使用Spring AOP实现日志管理 -->
      33     <aop:config>
      34         <!-- 定义切面 -->
      35         <aop:aspect id="logAspect" ref="logAspect">
      36             <!-- 定义切入点 -->
      37             <aop:pointcut  id="pointcut" expression="execution(* com.xxw.controller.*.*(..))" />
      38             <!-- 前值增强 -->
      39             <aop:before method="logBefore" pointcut-ref="pointcut" />
      40             <!-- 后置增强 -->
      41             <aop:after method="logAfter" pointcut-ref="pointcut" />
      42             <!-- 环绕增强 -->
      43             <!--<aop:around method="logAround" pointcut-ref="pointcut" />-->
      44         </aop:aspect>
      45     </aop:config>
      46 
      47     <!-- 上传拦截,配置文件上传 -->
      48     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      49         <!-- 默认编码 -->
      50         <property name="defaultEncoding" value="utf-8" />
      51         <!-- 文件大小最大字节 -->
      52         <property name="maxUploadSize" value="10485760000" />
      53         <!-- 内存中的最大值 -->
      54         <property name="maxInMemorySize" value="4096" />
      55         <!-- 启用是为了推迟文件解析,以便捕获文件大小异常 -->
      56         <property name="resolveLazily" value="true" />
      57     </bean>
      58 
      59     <!-- 视图解析器 -->
      60     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      61         <!-- 跳转的文件的前缀 -->
      62         <property name="prefix" value="/WEB-INF/jsp/" />
      63         <!-- 跳转的文件的后缀 -->
      64         <property name="suffix" value=".jsp" />
      65     </bean>
      66 
      67 </beans>
  6. mybatis-config.xml
    1. 1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">
      3 <configuration>
      4 
      5     <typeAliases>
      6         <typeAlias type="com.xxw.pojo.User" alias="User" />
      7     </typeAliases>
      8 
      9 </configuration>
      View Code
  7. web.xml
    1.  1 <?xml version="1.0" encoding="UTF-8"?>
       2 <!DOCTYPE web-app PUBLIC
       3  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
       4  "http://java.sun.com/dtd/web-app_2_3.dtd" >
       5 
       6 <web-app>
       7 
       8     <display-name>Archetype Created Web Application</display-name>
       9 
      10     <!-- Spring -->
      11     <context-param>
      12         <param-name>contextConfigLocation</param-name>
      13         <param-value>classpath:applicationContext-Main.xml</param-value>
      14     </context-param>
      15 
      16     <!-- Log4j -->
      17     <context-param>
      18         <param-name>log4jConfigLocation</param-name>
      19         <param-value>classpath:log4j.properties</param-value>
      20     </context-param>
      21     <context-param>
      22         <param-name>log4jRefreshInterval</param-name>
      23         <param-value>3000</param-value>
      24     </context-param>
      25 
      26     <!-- 编码格式 -->
      27     <filter>
      28         <filter-name>characterEncodingFilter</filter-name>
      29         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      30         <init-param>
      31             <param-name>encoding</param-name>
      32             <param-value>UTF-8</param-value>
      33         </init-param>
      34         <init-param>
      35             <param-name>forceEncoding</param-name>
      36             <param-value>true</param-value>
      37         </init-param>
      38     </filter>
      39     <filter-mapping>
      40         <filter-name>characterEncodingFilter</filter-name>
      41         <url-pattern>/*</url-pattern>
      42     </filter-mapping>
      43 
      44     <!-- Spring 监听 -->
      45     <listener>
      46         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      47     </listener>
      48 
      49     <!-- 监听Log4J 配置文件  -->
      50     <listener>
      51         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
      52     </listener>
      53 
      54     <!-- Servlet -->
      55     <servlet>
      56         <servlet-name>Spring</servlet-name>
      57         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      58         <init-param>
      59             <param-name>contextConfigLocation</param-name>
      60             <param-value>classpath:applicationContext-MVC.xml</param-value>
      61         </init-param>
      62         <load-on-startup>1</load-on-startup>
      63     </servlet>
      64     <servlet-mapping>
      65         <servlet-name>Spring</servlet-name>
      66         <url-pattern>/</url-pattern>
      67     </servlet-mapping>
      68 
      69     <!-- 初始化默认访问页面 -->
      70     <welcome-file-list>
      71         <welcome-file>index.jsp</welcome-file>
      72     </welcome-file-list>
      73 
      74 </web-app>
      View Code
  8. pom.xml
    1.   1 <?xml version="1.0" encoding="UTF-8"?>
        2 
        3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        5   <modelVersion>4.0.0</modelVersion>
        6 
        7   <groupId>com.xxw</groupId>
        8   <artifactId>MVCJedis</artifactId>
        9   <version>1.0-SNAPSHOT</version>
       10   <packaging>war</packaging>
       11 
       12   <name>MVCJedis Maven Webapp</name>
       13   <!-- FIXME change it to the project's website -->
       14   <url>http://www.example.com</url>
       15 
       16   <properties>
       17     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       18     <!-- spring 版本号 -->
       19     <spring.version>4.0.2.RELEASE</spring.version>
       20     <!-- mybatis 版本号 -->
       21     <mybatis.version>3.2.6</mybatis.version>
       22     <!-- log4j日志文件管理包版本 -->
       23     <slf4j.version>1.7.7</slf4j.version>
       24     <log4j.version>1.2.17</log4j.version>
       25   </properties>
       26 
       27   <!-- 依赖jar包 -->
       28   <dependencies>
       29 
       30     <!-- junit -->
       31     <dependency>
       32       <groupId>junit</groupId>
       33       <artifactId>junit</artifactId>
       34       <version>4.11</version>
       35       <!-- 表示开发时引入,发布时不会加载此包 -->
       36       <scope>test</scope>
       37     </dependency>
       38 
       39     <dependency>
       40       <groupId>org.aspectj</groupId>
       41       <artifactId>aspectjweaver</artifactId>
       42       <version>1.7.4</version>
       43     </dependency>
       44 
       45     <!-- spring 核心包 -->
       46     <dependency>
       47       <groupId>org.springframework</groupId>
       48       <artifactId>spring-core</artifactId>
       49       <version>${spring.version}</version>
       50     </dependency>
       51     <dependency>
       52       <groupId>org.springframework</groupId>
       53       <artifactId>spring-web</artifactId>
       54       <version>${spring.version}</version>
       55     </dependency>
       56     <dependency>
       57       <groupId>org.springframework</groupId>
       58       <artifactId>spring-oxm</artifactId>
       59       <version>${spring.version}</version>
       60     </dependency>
       61     <dependency>
       62       <groupId>org.springframework</groupId>
       63       <artifactId>spring-tx</artifactId>
       64       <version>${spring.version}</version>
       65     </dependency>
       66     <dependency>
       67       <groupId>org.springframework</groupId>
       68       <artifactId>spring-jdbc</artifactId>
       69       <version>${spring.version}</version>
       70     </dependency>
       71     <dependency>
       72       <groupId>org.springframework</groupId>
       73       <artifactId>spring-webmvc</artifactId>
       74       <version>${spring.version}</version>
       75     </dependency>
       76     <dependency>
       77       <groupId>org.springframework</groupId>
       78       <artifactId>spring-aop</artifactId>
       79       <version>${spring.version}</version>
       80     </dependency>
       81     <dependency>
       82       <groupId>org.springframework</groupId>
       83       <artifactId>spring-context-support</artifactId>
       84       <version>${spring.version}</version>
       85     </dependency>
       86     <dependency>
       87       <groupId>org.springframework</groupId>
       88       <artifactId>spring-test</artifactId>
       89       <version>${spring.version}</version>
       90     </dependency>
       91 
       92     <!-- mybatis 核心包 -->
       93     <dependency>
       94       <groupId>org.mybatis</groupId>
       95       <artifactId>mybatis</artifactId>
       96       <version>${mybatis.version}</version>
       97     </dependency>
       98 
       99     <!-- mybatis/spring 包 -->
      100     <dependency>
      101       <groupId>org.mybatis</groupId>
      102       <artifactId>mybatis-spring</artifactId>
      103       <version>1.2.2</version>
      104     </dependency>
      105 
      106     <!-- javaEE jar -->
      107     <dependency>
      108       <groupId>javax</groupId>
      109       <artifactId>javaee-api</artifactId>
      110       <version>7.0</version>
      111       <scope>provided</scope>
      112     </dependency>
      113 
      114     <!-- mysql 数据库连接 jar -->
      115     <dependency>
      116       <groupId>mysql</groupId>
      117       <artifactId>mysql-connector-java</artifactId>
      118       <version>5.1.30</version>
      119     </dependency>
      120 
      121     <!-- dbcp jar, 用来在applicationContext.xml中配置数据库 -->
      122     <dependency>
      123       <groupId>commons-dbcp</groupId>
      124       <artifactId>commons-dbcp</artifactId>
      125       <version>1.2.2</version>
      126     </dependency>
      127 
      128     <!-- JSTL标签类库 -->
      129     <dependency>
      130       <groupId>jstl</groupId>
      131       <artifactId>jstl</artifactId>
      132       <version>1.2</version>
      133     </dependency>
      134 
      135     <!-- 日志文件管理包 -->
      136     <dependency>
      137       <groupId>log4j</groupId>
      138       <artifactId>log4j</artifactId>
      139       <version>${log4j.version}</version>
      140     </dependency>
      141     <!-- 格式化对象,方便输出日志 -->
      142     <dependency>
      143       <groupId>com.alibaba</groupId>
      144       <artifactId>fastjson</artifactId>
      145       <version>1.1.41</version>
      146     </dependency>
      147     <dependency>
      148       <groupId>org.slf4j</groupId>
      149       <artifactId>slf4j-api</artifactId>
      150       <version>${slf4j.version}</version>
      151     </dependency>
      152     <dependency>
      153       <groupId>org.slf4j</groupId>
      154       <artifactId>slf4j-log4j12</artifactId>
      155       <version>${slf4j.version}</version>
      156     </dependency>
      157 
      158     <!-- 映射JSON -->
      159     <dependency>
      160       <groupId>org.codehaus.jackson</groupId>
      161       <artifactId>jackson-mapper-asl</artifactId>
      162       <version>1.9.13</version>
      163     </dependency>
      164 
      165     <!-- 上传组件包 -->
      166     <dependency>
      167       <groupId>commons-fileupload</groupId>
      168       <artifactId>commons-fileupload</artifactId>
      169       <version>1.3.1</version>
      170     </dependency>
      171     <dependency>
      172       <groupId>commons-io</groupId>
      173       <artifactId>commons-io</artifactId>
      174       <version>2.4</version>
      175     </dependency>
      176     <dependency>
      177       <groupId>commons-codec</groupId>
      178       <artifactId>commons-codec</artifactId>
      179       <version>1.9</version>
      180     </dependency>
      181 
      182     <!-- jedis jar -->
      183     <dependency>
      184       <groupId>redis.clients</groupId>
      185       <artifactId>jedis</artifactId>
      186       <version>2.9.0</version>
      187     </dependency>
      188 
      189   </dependencies>
      190 
      191   <build>
      192     <finalName>MVCJedis</finalName>
      193     <plugins>
      194       <plugin>
      195         <groupId>org.apache.maven.plugins</groupId>
      196         <artifactId>maven-compiler-plugin</artifactId>
      197         <configuration>
      198           <source>6</source>
      199           <target>6</target>
      200         </configuration>
      201       </plugin>
      202     </plugins>
      203   </build>
      204 </project>
      View Code

三、各种Java代码

  1. UserController.java
    1.  1 package com.xxw.controller;
       2 
       3 import com.xxw.pojo.User;
       4 import com.xxw.service.IUserService;
       5 import org.springframework.stereotype.Controller;
       6 import org.springframework.web.bind.annotation.RequestMapping;
       7 import org.springframework.web.bind.annotation.RequestMethod;
       8 import org.springframework.web.bind.annotation.ResponseBody;
       9 
      10 import javax.annotation.Resource;
      11 import java.util.List;
      12 
      13 @Controller
      14 @RequestMapping(value = "/user")
      15 public class UserController {
      16 
      17     @Resource(name = "IUserService")
      18     private IUserService service;
      19 
      20     @RequestMapping(value = "getUserList", method = RequestMethod.GET)
      21     @ResponseBody
      22     public Object getUserList() {
      23         List<User> list = null;
      24         try {
      25             list = service.getUserList();
      26         } catch (Exception e) {
      27             e.printStackTrace();
      28         }
      29 
      30         return list;
      31     }
      32 
      33 }
      View Code
  2. IUserService.java
    1.  1 package com.xxw.service;
       2 
       3 import com.xxw.pojo.User;
       4 
       5 import java.util.List;
       6 
       7 public interface IUserService {
       8 
       9     List<User> getUserList() throws Exception;
      10 
      11 }
      View Code
  3. UserServiceImpl.java
    1.  1 package com.xxw.service.impl;
       2 
       3 import com.xxw.dao.UserDao;
       4 import com.xxw.pojo.User;
       5 import com.xxw.service.IUserService;
       6 import org.springframework.stereotype.Service;
       7 
       8 import javax.annotation.Resource;
       9 import java.util.List;
      10 
      11 @Service(value = "IUserService")
      12 public class UserServiceImpl  implements IUserService {
      13 
      14     @Resource(name = "UserDao")
      15     private UserDao dao;
      16 
      17 
      18     @Override
      19     public List<User> getUserList()throws Exception {
      20         return dao.findUserList();
      21     }
      22 
      23 }
      View Code
  4. UserDao.java
    1.  1 package com.xxw.dao;
       2 
       3 import com.xxw.pojo.User;
       4 import org.mybatis.spring.SqlSessionTemplate;
       5 import org.springframework.beans.factory.annotation.Autowired;
       6 import org.springframework.stereotype.Repository;
       7 
       8 import java.util.List;
       9 
      10 @Repository(value = "UserDao")
      11 public class UserDao {
      12 
      13     @Autowired
      14     SqlSessionTemplate sqlSessionTemplate;
      15 
      16     public List<User> findUserList()throws Exception{
      17         return sqlSessionTemplate.selectList("UserMapper.findUserList");
      18     }
      19 
      20 }
      View Code
  5. User.java
    1.  1 package com.xxw.pojo;
       2 
       3 public class User {
       4 
       5     private String id = null;      // 用户ID
       6     private String name = null;    // 用户名
       7     private int age = -1;          // 年龄
       8     private String gender = null;  // 性别
       9     private String address = null; // 用户地址
      10     private String phone = null;   // 电话
      11 
      12     public String getId() {
      13         return id;
      14     }
      15 
      16     public void setId(String id) {
      17         this.id = id;
      18     }
      19 
      20     public String getName() {
      21         return name;
      22     }
      23 
      24     public void setName(String name) {
      25         this.name = name;
      26     }
      27 
      28     public int getAge() {
      29         return age;
      30     }
      31 
      32     public void setAge(int age) {
      33         this.age = age;
      34     }
      35 
      36     public String getGender() {
      37         return gender;
      38     }
      39 
      40     public void setGender(String gender) {
      41         this.gender = gender;
      42     }
      43 
      44     public String getAddress() {
      45         return address;
      46     }
      47 
      48     public void setAddress(String address) {
      49         this.address = address;
      50     }
      51 
      52     public String getPhone() {
      53         return phone;
      54     }
      55 
      56     public void setPhone(String phone) {
      57         this.phone = phone;
      58     }
      59 }
      View Code
  6. LoggerAspect
    1.  1 package com.xxw.util;
       2 
       3 import org.aspectj.lang.JoinPoint;
       4 import org.slf4j.Logger;
       5 import org.slf4j.LoggerFactory;
       6 
       7 import java.text.SimpleDateFormat;
       8 import java.util.Date;
       9 
      10 public class LoggerAspect {
      11 
      12     private final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);
      13 
      14     /**
      15      * 前置信息
      16      * @param joinPoint
      17      * @throws Exception
      18      */
      19     public void logBefore(JoinPoint joinPoint) throws  Exception{
      20         logger.info(getInformation(joinPoint)+"---- start");
      21     }
      22 
      23     /**
      24      * 后置信息
      25      * @param joinPoint
      26      * @throws Exception
      27      */
      28     public void logAfter(JoinPoint joinPoint) throws  Exception{
      29         logger.info(getInformation(joinPoint)+"---- end");
      30     }
      31 
      32     /**
      33      * 生成描述信息
      34      * @param joinPoint
      35      * @return
      36      * @throws Exception
      37      */
      38     private String getInformation(JoinPoint joinPoint) throws  Exception{
      39         // 获取类名
      40         String targetName = joinPoint.getTarget().getClass().getName();
      41         // 获取方法名
      42         String methodName = joinPoint.getSignature().getName();
      43         // 当前时间
      44         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      45         return sdf.format(new Date())+"----:"+targetName+"."+methodName;
      46     }
      47 
      48 }
  7. AnnotationLoggerAspect
    1.  1 package com.xxw.util;
       2 
       3 import org.aspectj.lang.JoinPoint;
       4 import org.aspectj.lang.annotation.After;
       5 import org.aspectj.lang.annotation.Aspect;
       6 import org.aspectj.lang.annotation.Before;
       7 import org.slf4j.Logger;
       8 import org.slf4j.LoggerFactory;
       9 import org.springframework.stereotype.Component;
      10 
      11 import java.text.SimpleDateFormat;
      12 import java.util.Date;
      13 
      14 @Aspect
      15 @Component
      16 /**
      17  * 注解增强
      18  */
      19 public class AnnotationLoggerAspect {
      20 
      21     private final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);
      22 
      23     /**
      24      * 前置信息
      25      * @param joinPoint
      26      * @throws Exception
      27      */
      28     @Before(value = "execution(* com.xxw.controller.*.*(..))")
      29     public void logBefore(JoinPoint joinPoint) throws  Exception{
      30         logger.info(getInformation(joinPoint)+"---- start");
      31     }
      32 
      33     /**
      34      * 后置信息
      35      * @param joinPoint
      36      * @throws Exception
      37      */
      38     @After(value = "execution(* com.xxw.controller.*.*(..))")
      39     public void logAfter(JoinPoint joinPoint) throws  Exception{
      40         logger.info(getInformation(joinPoint)+"---- end");
      41     }
      42 
      43     /**
      44      * 生成描述信息
      45      * @param joinPoint
      46      * @return
      47      * @throws Exception
      48      */
      49     private String getInformation(JoinPoint joinPoint) throws  Exception{
      50         // 获取类名
      51         String targetName = joinPoint.getTarget().getClass().getName();
      52         // 获取方法名
      53         String methodName = joinPoint.getSignature().getName();
      54         // 当前时间
      55         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      56         return sdf.format(new Date())+"----:"+targetName+"."+methodName;
      57     }
      58 
      59 }

四、还有几个文件

  1. UserMapper.xml
    1. 1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      3 <mapper namespace="UserMapper">
      4 
      5     <select id="findUserList" resultType="User">
      6         SELECT ID, NAME, AGE, GENDER, PHONE, ADDRESS FROM USER
      7     </select>
      8 
      9 </mapper>
      View Code
  2. user.sql
    1.  1 /*
       2 SQLyog Ultimate v12.09 (64 bit)
       3 MySQL - 5.7.17-log : Database - company
       4 *********************************************************************
       5 */
       6 
       7 
       8 /*!40101 SET NAMES utf8 */;
       9 
      10 /*!40101 SET SQL_MODE=''*/;
      11 
      12 /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
      13 /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
      14 /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
      15 /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
      16 CREATE DATABASE /*!32312 IF NOT EXISTS*/`company` /*!40100 DEFAULT CHARACTER SET utf8 */;
      17 
      18 USE `company`;
      19 
      20 /*Table structure for table `user` */
      21 
      22 DROP TABLE IF EXISTS `user`;
      23 
      24 CREATE TABLE `user` (
      25   `id` varchar(20) NOT NULL COMMENT '员工编号',
      26   `password` varchar(50) DEFAULT NULL COMMENT '员工密码',
      27   `name` varchar(20) DEFAULT NULL COMMENT '员工姓名',
      28   `age` int(2) DEFAULT NULL COMMENT '员工年龄',
      29   `gender` char(2) DEFAULT NULL COMMENT '员工性别',
      30   `phone` decimal(11,0) DEFAULT NULL COMMENT '员工电话',
      31   `address` varchar(200) DEFAULT NULL COMMENT '员工住址',
      32   PRIMARY KEY (`id`)
      33 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      34 
      35 /*Data for the table `user` */
      36 
      37 LOCK TABLES `user` WRITE;
      38 
      39 insert  into `user`(`id`,`password`,`name`,`age`,`gender`,`phone`,`address`) values ('021ef','13465','test3',22,'','18311546235','北京天桥'),('4845a','123465','test1',NULL,'','15236987421','北京天桥'),('a73bf','123456','test2',NULL,'','15896477432','北京天桥'),('P00001','123456','小二',19,'','15811234884','北京天桥'),('P00002','123456','小三',20,'','18823854512','北京天桥'),('P00003','123456','小四',21,'','15862154512','北京天桥'),('P00004','123456','小五',22,'','15895456412','北京天桥'),('P00005','123456','小六',18,'','18856412345','北京天桥'),('P00006','123456','小七',19,'','18456125451','北京天桥'),('P00007','123456','小八',20,'','13694564564','北京天桥'),('P00008','123456','小九',21,'','18736542541','北京天桥'),('V00001','123456','小一',18,'','18811471169','北京天桥'),('V152171','123456','小十',22,'','15832456368','北京天桥');
      40 
      41 UNLOCK TABLES;
      42 
      43 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
      44 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
      45 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
      46 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
      View Code

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:IntelliJ IDEA远程调试运行中的JAVA程序/项目

下一篇:git命令设置