zoukankan      html  css  js  c++  java
  • Spring AOP的日志记录

      现在的项目是Spring+MyBatis,前段时间项目经理让我干了一个活,就是给所有的controller里的所有方法加上日志记录的代码,其实没有多少,也就300来个方法,也没有抱怨什么,一边打着瞌睡一边就干了,干的活如下:

      举例:

      

    private static Log log = LogFactory.getLog(UserController.class);
    @RequestMapping("/sys/user/query.do")
    public String sysUserQuery(HttpServletRequest request, ModelMap map) throws Exception {
            String thisMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
            log.info(thisMethodName+":start");//开始日止记录
            log.info(thisMethodName+":end");//结束日止记录
            return "sys/user/sysUserQuery";
        }            

      像这样重复的代码,我竟然干了300多次。

      我想,项目进行到最后才加的日志记录一定是因为有某种原因才使用这种日志记录的方法吧,但是当初使用Spring的时候,他的一大亮点不就是因为AOP实现的日志管理功能吗?所以一定要尝试一次,理解AOP怎么通过动态代理完成日志管理的。

      下面是一个简单的例子:

      备注:这个例子是在博客:Spring和MyBatis环境整合 的例子的基础上做,暂时以方法调用前的日志通知为例。

      

      1、model----User.java

      

     1 package com.springMyBatis.system.model;
     2 
     3 public class User {
     4     private int id;
     5     private String username;
     6     private String password;
     7     public User(){}
     8     public int getId() {
     9         return id;
    10     }
    11     public void setId(int id) {
    12         this.id = id;
    13     }
    14     public String getUsername() {
    15         return username;
    16     }
    17     public void setUsername(String username) {
    18         this.username = username;
    19     }
    20     public String getPassword() {
    21         return password;
    22     }
    23     public void setPassword(String password) {
    24         this.password = password;
    25     }
    26     public String toString(){
    27         return "User[id="+id+" , username="+username+" , password="+password+"]";
    28     }
    29     
    30 
    31 }

     

     

     

     

       2、Dao 接口----UserDao.java

      

     1 package com.springMyBatis.system.dao;
     2 
     3 import com.springMyBatis.system.model.User;
     4 
     5 public interface UserDao {
     6     public User getUser(User user);
     7     public void addUser(User user);
     8     public void updateUser(User user);
     9     public void deleteUser(int UserId);
    10 }

      3、Dao----UserDao.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
     3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
     4 <mapper namespace="com.springMyBatis.system.dao.UserDao">  
     5 <select id="getUser" parameterType="com.springMyBatis.system.model.User" resultType="com.springMyBatis.system.model.User">  
     6     SELECT * FROM user WHERE username=#{username} AND password=#{password}  
     7 </select>  
     8 <insert id="addUser" parameterType="com.springMyBatis.system.model.User" flushCache="true">  
     9    INSERT INTO user (id,username,password) VALUES (#{id},#{username},#{password})  
    10 </insert>  
    11 <update id="updateUser" parameterType="com.springMyBatis.system.model.User">  
    12     UPDATE user SET password=#{password} WHERE id=#{id}  
    13 </update>  
    14 <delete id="deleteUser" parameterType="int">  
    15     DELETE FROM user WHERE id=#{id}  
    16 </delete>  
    17 </mapper>  

     

       4、业务---UserBiz.java

      

     1 package com.springMyBatis.system.biz;
     2 
     3 import com.springMyBatis.system.model.User;
     4 
     5 public interface UserBiz {
     6     //添加用户
     7      public void addUser(User user);
     8      //删除用户
     9      public void delUser(int id);
    10 }

      业务实现---UserBizImpl.java

      

     1 package com.springMyBatis.system.biz;
     2 
     3 import com.springMyBatis.system.dao.UserDao;
     4 import com.springMyBatis.system.model.User;
     5 
     6 public class UserBizImpl implements UserBiz {
     7 
     8     UserDao userdao;
     9 
    10      public UserDao getUserdao() {
    11      return userdao;
    12      }
    13 
    14      public void setUserdao(UserDao userdao) {
    15      this.userdao = userdao;
    16      }
    17 
    18      public void addUser(User user) {
    19      userdao.addUser(user);
    20      }
    21 
    22      public void delUser(int id) {
    23      // TODO Auto-generated method stub
    24      userdao.deleteUser(id);
    25      }
    26 
    27 }

      5、Advice类

     1 package com.springMyBatis.aop;
     2 import java.lang.reflect.Method;
     3 import org.apache.log4j.Logger;
     4 import org.springframework.aop.MethodBeforeAdvice;
     5 public class LoggerAdvice implements MethodBeforeAdvice{
     6      private Logger logger = Logger.getLogger(LoggerAdvice.class);
     7     @Override
     8     public void before(Method method, Object[] args, Object target)
     9             throws Throwable {
    10         //类名
    11         String targetClassName=target.getClass().getName();
    12         //获取被调用的方法名
    13         String targetMethodName=method.getName();
    14         //显示日志的格式字符串
    15         String loginInfoText="前置通知"+targetClassName+"类的"+targetMethodName+"方法开始执行";
    16         logger.info(loginInfoText);
    17     }
    18 }

       6、log4j.properties

      

    log4j.rootLogger=info,stdout,info,debug,error
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
     
    log4j.logger.info=info
    log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.info.layout=org.apache.log4j.PatternLayout
    log4j.appender.info.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
    log4j.appender.info.datePattern='.'yyyy-MM-dd
    log4j.appender.info.Threshold = INFO 
    log4j.appender.info.append=true
    log4j.appender.info.File=D:/info.log

      7、mybatis-config.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>  
        <mappers>  
            <mapper resource="com/springMyBatis/system/dao/UserDao.xml"/>  
        </mappers>  
    </configuration>  

       8、ApplicationContext.xml

      

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans  
     3     xmlns="http://www.springframework.org/schema/beans"  
     4     xmlns:tx="http://www.springframework.org/schema/tx"  
     5     xmlns:p="http://www.springframework.org/schema/p"  
     6     xmlns:aop="http://www.springframework.org/schema/aop"   
     7     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     8     xsi:schemaLocation="http://www.springframework.org/schema/beans   
     9     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    10     http://www.springframework.org/schema/tx   
    11     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
    12     http://www.springframework.org/schema/aop    
    13     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
    14 <!-- 配置数据源-->  
    15     <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    16     <property name="driverClassName">  
    17         <value>org.gjt.mm.mysql.Driver</value>  
    18     </property>  
    19     <property name="url">  
    20         <value>jdbc:mysql://localhost:3306/springmybaitis?useUnicode=true&amp;characterEncoding=UTF-8</value>  
    21        <!--springmybaitis是我的数据库  -->
    22     </property>  
    23     <property name="username">  
    24         <value>root</value>  
    25     </property>  
    26     <property name="password">  
    27         <value>123456</value>  
    28     </property>  
    29 </bean>  
    30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    31     <property name="dataSource" ref="jdbcDataSource" />  
    32     <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
    33 </bean>  
    34 <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    35     <property name="mapperInterface" value="com.springMyBatis.system.dao.UserDao"></property>  
    36     <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
    37 </bean>
    38  <!-- 配置创建UserBizImpl的实例 -->
    39  <bean id="userBiz" class="com.springMyBatis.system.biz.UserBizImpl">
    40  <!-- 依赖注入数据访问层组件 -->
    41  <property name="userdao" ref="userDao" />
    42  </bean>  
    43 <!-- 定义前置通知 -->
    44 <bean id="logAdvice" class="com.springMyBatis.aop.LoggerAdvice"></bean>
    45 <!-- 定义代理类 -->
    46 <bean id="ub" class="org.springframework.aop.framework.ProxyFactoryBean">
    47     <property name="proxyInterfaces">
    48         <!-- <value>com.springMyBatis.system.dao.UserDao</value> -->
    49         <value>com.springMyBatis.system.biz.UserBiz</value>
    50     </property>
    51     <property name="interceptorNames">
    52         <list>
    53             <value>logAdvice</value>
    54         </list>
    55     </property>
    56     <property name="target" ref="userBiz"></property>
    57 </bean>
    58 
    59 </beans>  

       9、测试结果:

      

     1 package com.springMyBatis.system.test;
     2 
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.support.ClassPathXmlApplicationContext;
     5 
     6 import com.springMyBatis.system.biz.UserBiz;
     7 import com.springMyBatis.system.dao.UserDao;
     8 import com.springMyBatis.system.model.User;
     9 
    10 public class Test {
    11 
    12     /**
    13      * @param args
    14      */
    15     public static void main(String[] args) {
    16         // TODO Auto-generated method stub
    17         ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
    18          //装配UserbIZimpl事例化
    19          UserBiz userbiz = (UserBiz) context.getBean("ub");
    20          User user=new User();
    21          user.setId(1);
    22          user.setPassword("123");
    23          user.setUsername("Jessica");
    24          userbiz.addUser(user);
    25          user.setId(2);
    26          user.setPassword("123");
    27          user.setUsername("Jessica2");
    28          userbiz.addUser(user);
    29          user.setId(3);
    30          user.setPassword("123");
    31          user.setUsername("Jessica3");
    32          userbiz.addUser(user);
    33          user.setId(4);
    34          user.setPassword("123");
    35          user.setUsername("Jessica4");
    36          userbiz.addUser(user);
    37          userbiz.delUser(1);
    38          
    39         
    40 
    41     }
    42 
    43 }

      日志:

      

    [INFO ] [15:21:32] org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7a78d3: startup date [Wed Jul 30 15:21:32 CST 2014]; root of context hierarchy
    [INFO ] [15:21:32] org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
    [INFO ] [15:21:32] org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2a15cd: defining beans [jdbcDataSource,sqlSessionFactory,userDao,userBiz,logAdvice,ub]; root of factory hierarchy
    [INFO ] [15:21:32] org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: org.gjt.mm.mysql.Driver
    [INFO ] [15:21:33] com.springMyBatis.aop.LoggerAdvice - 前置通知com.springMyBatis.system.biz.UserBizImpl类的addUser方法开始执行
    [INFO ] [15:21:34] com.springMyBatis.aop.LoggerAdvice - 前置通知com.springMyBatis.system.biz.UserBizImpl类的addUser方法开始执行
    [INFO ] [15:21:34] com.springMyBatis.aop.LoggerAdvice - 前置通知com.springMyBatis.system.biz.UserBizImpl类的addUser方法开始执行
    [INFO ] [15:21:34] com.springMyBatis.aop.LoggerAdvice - 前置通知com.springMyBatis.system.biz.UserBizImpl类的addUser方法开始执行
    [INFO ] [15:21:34] com.springMyBatis.aop.LoggerAdvice - 前置通知com.springMyBatis.system.biz.UserBizImpl类的delUser方法开始执行

      通过这样的方式,我们只需要定义一个Advice类,实现Spring里的4中Advice接口(环绕Advice、Before Advice、After advice、Throws Advice),再在配置里配置好就可以了。哪里用写300次呢?我们有动态代理可以为我们做这些事情,就不必亲自动手啦。

      

  • 相关阅读:
    [转] 一封程序员的情书
    [**收集**]实用的网站
    [转] 绝对实用!60款免费软件逐个点评下载
    [*日语学习笔记*] 大家的日语初级1动词活用笔记
    [转] IT人不可不听的10个职场故事
    【转图】从可乐到NIKE 经典logo的web2.0版
    [转] 常用姓氏读法
    [转] 数据库开发个人总结(ADO.NET小结)
    [转] VB十七种可用一行代码完成的技巧
    [转] 程序员爱情观XP版本 (敏捷版本)
  • 原文地址:https://www.cnblogs.com/jyh317/p/3875546.html
Copyright © 2011-2022 走看看