1. 程式人生 > 程式設計 >Spring框架實現AOP新增日誌記錄功能過程詳解

Spring框架實現AOP新增日誌記錄功能過程詳解

這篇文章主要介紹了Spring框架實現AOP新增日誌記錄功能過程詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

需求,在呼叫業務方法的時候,在被呼叫的業務方法的前面和後面新增上日誌記錄功能

整體架構:

日誌處理類:

package aop;

import java.util.Arrays;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;

//日誌處理類 增強處理類-日誌
public class UserServiceLogger {
  private Logger logger = Logger.getLogger(UserServiceLogger.class);

  // 前置增強
  public void before(JoinPoint joinPoint) {
    logger.info("呼叫" + joinPoint.getTarget() + "的"
        + joinPoint.getSignature() + "方法,方法引數是:"
        + Arrays.toString(joinPoint.getArgs()));
  }

  // 後置增強
  public void afterReturning(JoinPoint joinPoint,Object result) {
    logger.info("呼叫" + joinPoint.getTarget() + "的"
        + joinPoint.getSignature() + "方法,方法的返回值是:"
        +result);
  }
}
下面是一個三層架構模式: 
package dao;

import entity.User;

/**
 * 增加DAO介面,定義了所需的持久化方法
 */
public interface UserDao {
  public void save(User user);
}
package dao.impl;

import dao.UserDao;
import entity.User;

/**
 * 使用者DAO類,實現IDao介面,負責User類的持久化操作
 */
public class UserDaoImpl implements UserDao {

  public void save(User user) {
    // 這裡並未實現完整的資料庫操作,僅為說明問題
    System.out.println("儲存使用者資訊到資料庫");
  }
}
package entity;

/**
 * 使用者實體類
 */
public class User implements java.io.Serializable {
  private Integer id; // 使用者ID
  private String username; // 使用者名稱
  private String password; // 密碼
  private String email; // 電子郵件

  // getter & setter
  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

}
package service;

import entity.User;

/**
 * 使用者業務介面,定義了所需的業務方法
 */
public interface UserService {
  public void addNewUser(User user);
}
package service.impl;

import service.UserService;
import dao.UserDao;
import entity.User;

/**
 * 使用者業務類,實現對User功能的業務管理
 */
public class UserServiceImpl implements UserService {

  // 宣告介面型別的引用,和具體實現類解耦合
  private UserDao dao;

  // dao 屬性的setter訪問器,會被Spring呼叫,實現設值注入
  public void setDao(UserDao dao) {
    this.dao = dao;
  }

  public void addNewUser(User user) {
    // 呼叫使用者DAO的方法儲存使用者資訊
    dao.save(user);
  }
}
編寫單元測試方法:
package test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import service.UserService;
import service.impl.UserServiceImpl;

import entity.User;


public class AopTest {

  @Test
  public void aopTest() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService service = (UserService) ctx.getBean("service");
    
    User user = new User();
    user.setId(1);
    user.setUsername("test");
    user.setPassword("123456");
    user.setEmail("[email protected]");

    service.addNewUser(user);
  }

}

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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
  <bean id="dao" class="dao.impl.UserDaoImpl"></bean>
  <bean id="service" class="service.impl.UserServiceImpl">
    <property name="dao" ref="dao"></property>
  </bean>
  <!-- 宣告增強方法所在的Bean -->
  <bean id="theLogger" class="aop.UserServiceLogger"></bean>
  <!-- 配置切面 -->
  <aop:config>
    <!-- 定義切入點 -->
    <aop:pointcut id="pointcut"
      expression="execution(public void addNewUser(entity.User))" />
    <!-- 引用包含增強方法的Bean -->
    <aop:aspect ref="theLogger">
      <!-- 將before()方法定義為前置增強並引用pointcut切入點 -->
      <aop:before method="before" pointcut-ref="pointcut"></aop:before>
      <!-- 將afterReturning()方法定義為後置增強並引用pointcut切入點 -->
      <!-- 通過returning屬性指定為名為result的引數注入返回值 -->
      <aop:after-returning method="afterReturning"
  
     pointcut-ref="pointcut" returning="result" />
    </aop:aspect>
  </aop:config>
</beans>

執行結果:

12-29 15:13:06[INFO]org.springframework.context.support.ClassPathXmlApplicationContext
 -Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2db0f6b2: startup date [Sun Dec 29 15:13:06 CST 2019]; root of context hierarchy
12-29 15:13:06[INFO]org.springframework.beans.factory.xml.XmlBeanDefinitionReader
 -Loading XML bean definitions from class path resource [applicationContext.xml]
12-29 15:13:06[INFO]org.springframework.beans.factory.support.DefaultListableBeanFactory
 -Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3701eaf6: defining beans [userDao,service,theLogger,org.springframework.aop.config.internalAutoProxyCreator,pointcut,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1]; root of factory hierarchy
12-29 15:13:06[INFO]aop.UserServiceLogger
 -呼叫service.impl.UserServiceImpl@3c130745的void service.UserService.addNewUser(User)方法,方法引數是:[entity.User@2e4b8173]
儲存使用者資訊到資料庫
12-29 15:13:06[INFO]aop.UserServiceLogger
 -呼叫service.impl.UserServiceImpl@3c130745的void service.UserService.addNewUser(User)方法,方法的返回值是:null

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。