spring框架學習6:spring-aop的五種通知類型


使用springaop時需要注意,如果bean對象,即service層的對象沒有實現接口的話,使用spring-aop的話會報錯,因此需要在service層創建接口。

spring-aop的基層是基於動態代理來實現的,動態代理的實現有兩種方式:

1.jdk動態代理

  spring模式默認使用jdk動態代理,jdk動態代理要求目標類的對象必須實現一個接口,而且獲取目標類對象的時候要做向上轉型為接口。

2.cglib動態代理

  cglib代理方式spring aop也支持,cglib實現動態代理的時候,不需要目標類實現接口,如果要把spring aop的代理方式改為cglib,需要如下配置:

  

  proxy-target-class如果設置成true使用cglib動態代理,默認是false使用jdk動態代理。
spring的五種通知類型:
通知類型 說明
aop:before 前置通知 在目標方法調用之前執行
aop:after-returning后置通知 在目標方法調用之后執行,一旦目標方法產生異常不會執行
aop:after 最終通知 在目標調用方法之后執行,無論目標方法是否產生異常,都會執行
aop:after-throwing 異常通知 在目標方法產生異常時執行
aop:around 環繞通知 在目標方法執行之前和執行之后都會執行,可以寫一些非核心的業務邏輯,一般用來替代前置通知和后置通知
 
 
 
 
 
 
 
 
 
 
 
 
使用注解的方式配置spring-aop:
1.創建通知類
package com.zs.advice;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 用戶業務通知
 */
@Component
@Aspect
public class UserAdvice {

    @After("execution(void *User(..))")
    public void log() {
        System.out.println("生成日志文件");
    }

    @Before("execution(void *User(..))")
    public void yanzheng() {
        System.out.println("驗證數據");
    }

    @AfterThrowing(pointcut = "execution(void *User(..))",throwing = "e")
    public void error(Exception e) {
        System.out.println("異常處理");
    }
}
 
2.spring配置文件中聲明使用注解的方式配置spring-aop;
<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--聲明service對象-->
    <bean id="userService" class="com.zs.service.impl.UserServiceImpl"/>

    <!--掃描通知類包-->
    <context:component-scan base-package="com.zs.advice"/>
    <!--聲明以注解的方式配置spring-aop-->
    <aop:aspectj-autoproxy/>
</beans>

3.測試

import com.zs.entity.User; import com.zs.service.UserService; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AopTest { private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); @Test public void fun1() { UserService us = (UserService) context.getBean("userService"); us.saveUser(new User()); } }

結果如下:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM