spring aop 使用注解方式總結


spring aop的注解方式:和xml的配置方式略有區別,詳細如下:

1、首先還是建立需要的切面類:切面類里面定義好切點配置,以及所有的需要實現的通知方法。

/**
 * 
 */
package com.lilin.maven.service.annotationaop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

/**
 * @author lilin
 * 
 */
@Aspect
@Service
public class AspectAop {

    /**
     * 申明切點,同時配置將要被aop過濾的業務類
     */
    @Pointcut("execution (* com.lilin.maven.service.annotationaop.UserService.addUser(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void doBefore() {
        System.out.println("doBefore advice");
    }

    @AfterReturning("pointcut()")
    public void doAfterReturning() {
        System.out.println("doAfterReturning advice");
    }

    @After("pointcut()")
    public void doAfter() {
        System.out.println("doAfter advice");
    }

    @AfterThrowing("pointcut()")
    public void doAfterThrowing() {
        System.out.println("doAfterThrowing advice");
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("doAround advice start");
        Object result = pjp.proceed();
        System.out.println("doAround advice end");
        return result;
    }

}

2、在spring的配置文件中,開啟注解的掃描:

<?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-2.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置注解掃面路徑 -->
    <context:component-scan base-package="com.lilin" />
    <!-- 開啟注解 -->
    <context:annotation-config />
    <!-- 開啟aspectj代理 -->
    <aop:aspectj-autoproxy />
</beans>

3、建立業務的接口和類,方便aop的過濾測試。

/**
 * 
 */
package com.lilin.maven.service.annotationaop;

/**
 * @author lilin
 * 
 */
public interface IUserService {
    void addUser();
}
/**
 * 
 */
package com.lilin.maven.service.annotationaop;

import org.springframework.stereotype.Service;

/**
 * @author lilin
 * 
 */
@Service
public class UserService implements IUserService {
    @Override
    public void addUser() {
        System.out.println("增加用戶信息");
     //這個異常信息的拋出,是為了測試after throwing的advice的
throw new RuntimeException("測試異常"); } }

4、還是像xml配置的時候類似,建立testNG的測試類:繼承的baseTest 和xml配置的中一樣,請參見上一篇xml配置中的baseTest

/**
 * 
 */
package com.lilin.maven.service.annotationaop;

import javax.annotation.Resource;

import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;

import com.lilin.maven.service.BaseTest;

/**
 * @author lilin
 * 
 */
@ContextConfiguration(locations = { "classpath:/config/spring/spring-aopannotation.xml" })
public class AopAnnotationTest extends BaseTest {

    @Resource
    private IUserService userService;

    @Test
    public void aopAnnotationTest() {
        userService.addUser();
    }

}

5、運行測試方法,可以得到注解方式的aop配置已經起到作用:

正常的測試結果如下:

2016-1-29 15:25:09 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config/spring/spring-aopannotation.xml]
2016-1-29 15:25:09 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@10f6d3: startup date [Fri Jan 29 15:25:09 CST 2016]; root of context hierarchy
2016-1-29 15:25:09 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@10721b0: defining beans [aspectAop,userService,light,lightOnCommand,remoteControl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
doAround advice start
doBefore advice
增加用戶信息
doAround advice end
doAfter advice
doAfterReturning advice
PASSED: aopAnnotationTest

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

@AfterThrowing 的測試結果如下,測試這個,請手動在業務方法里面拋出異常信息:

2016-1-29 15:26:50 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config/spring/spring-aopannotation.xml]
2016-1-29 15:26:50 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@10f6d3: startup date [Fri Jan 29 15:26:50 CST 2016]; root of context hierarchy
2016-1-29 15:26:50 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@10721b0: defining beans [aspectAop,userService,light,lightOnCommand,remoteControl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
doAround advice start
doBefore advice
增加用戶信息
doAfter advice
doAfterThrowing advice
FAILED: aopAnnotationTest
java.lang.RuntimeException: 測試異常
    at com.lilin.maven.service.annotationaop.UserService.addUser(UserService.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

好了,到此,spring aop的注解方式的實現,一個簡單的demo就o了。

 


免責聲明!

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



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