Spring使用注解创建切面

(接上篇Spring通过切点来选择连接点)

定义切面:

        下面将展示Audience类,它定义了一个切面:

package main.java;

import org.aspectj.lang.annotation.*;

/**
 * @author [email protected]
 * @date 18-4-18 上午8:56
 */

@Aspect
public class Audience {
    @Pointcut("execution(** main.java.Performance.perform(..))")
    public void performance() {}

    @Before("performance()")
    public void silenceCellPhones(){
        System.out.println("Silecing cell phones");
    }

    @Before("performance()")
    public void takeSeats(){
        System.out.println("Taking seats");
    }
    
    @AfterReturning("performance()")
    public void applause(){
        System.out.println("CLAP CLAP CLAP");
    }
    
    @AfterThrowing("performance()")
    public void demandRefund(){
        System.out.println("Demanding a refund");
    }
}

        Audience类使用了@AspectJ注解进行了标注.该注解表明Audience不仅仅是一个POJO,还是一个切面.

        AspectJ提供了五个注解来定义通知:

注解 通知
@After 通知方法会在目标方法返回或抛出异常后调用
@AfterReturning 通知方法会在目标方法返回后调用
@AfterThrowing 通知方法会在目标方法抛出异常后调用
@Around 通知方法会将目标方法封装起来
@Before 通知方法会在目标方法调用之前执行

            以上注解都要给定一个切点表达式作为它的值

        在Audience类中,performance方法使用了@Pointcut注解,为该注解设置的值是一个切点表达式;设置之后,可以用Performance代替冗长的切点表达式.


在JavaConfig中设置自动代理:

package main.java;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author [email protected]
 * @date 18-4-18 上午9:24
 */

@Configuration
@EnableAspectJAutoProxy
public class Config {
    @Bean
    public Audience audience(){
        return new Audience();
    }
}

        在类级别上使用@EnableAspectJProxy注解启用自动代理功能.


在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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="main.java"/>

    <!--启用AspectJ自动代理-->
    <aop:aspectj-autoproxy/>

    <!--声明Audience Bean-->
    <bean id="Audience" class="main.java.Audience"/>

</beans>

    不管是JavaConfig还是XML,AspectJ自动代理都会为使用@Aspect注解的Bean创建一个代理,这个代理会围绕着所有该切面的切点所匹配的Bean.这种情况下,将会为main.java bean创建一个代理,Audience类中的通知方法将会在perform()调用前后执行.


创建环绕通知: 

package main.java;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

/**
 * @author [email protected]
 * @date 18-4-18 上午8:56
 */

@Aspect
public class Audience {
    @Pointcut("execution(** main.java.Performance.perform(..))")
    public void performance() {}

    @Around("performance()")
    public void watchPerformance(ProceedingJoinPoint joinPoint){
        try{
            System.out.println("Silecing cell phones");
            System.out.println("Taking seats");
            joinPoint.proceed();
            System.out.println("CLAP CLAP CLAP");
        }catch (Throwable e){
            System.out.println("Demanding a refund");
        }
    }
}

        @Around注解表明watchPerformance()方法会做为Performance()切点的环绕通知.该通知达到的效果与上面四个通知达到的效果是一样的.

        关于环绕通知,它接受ProceedingJoinPoint作为参数,必须要有这个对象,因为要在通知中通过此参数调用被通知的方法.

        如果忘记调用proceed()方法,会阻塞对被通知方法的调用.


对以上代码进行测试:

package main.java;

import org.springframework.stereotype.Component;

/**
 * @author [email protected]
 * @date 18-4-18 上午9:48
 */

public class VinaPerform implements Performance {
    @Override
    public void perform() {
        System.out.println("Vina is singing");
    }
}
        创建一个实现类.
package main.java;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author [email protected]
 * @date 18-4-18 上午9:24
 */

@Configuration
@EnableAspectJAutoProxy
public class Config {
    @Bean
    public VinaPerform vinaPerform(){
        return new VinaPerform();
    }

    @Bean
    public Audience audience(){
        return new Audience();
    }
}

        JavaConfig配置文件如上;

package main.java;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author [email protected]
 * @date 18-4-18 上午9:46
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = main.java.Config.class)
public class Test {
    @Autowired
    private Performance performance;

    @org.junit.Test
    public void AudienceTest(){
        performance.perform();
    }
} 
          测试代码如上,测试结果为:
四月 18, 2018 10:30:19 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
四月 18, 2018 10:30:19 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@26ba2a48, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5f2050f6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3b81a1bc, org.springframework.test.context.transaction.TransactionalTestExecutionListener@64616ca2, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@13fee20c]
四月 18, 2018 10:30:19 上午 org.springframework.context.support.GenericApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@2ef5e5e3: startup date [Wed Apr 18 10:30:19 CST 2018]; root of context hierarchy
Silecing cell phones
Taking seats
Vina is singing
CLAP CLAP CLAP

Process finished with exit code 0
        测试结果和预期一样.

猜你喜欢

转载自blog.csdn.net/weixin_41704428/article/details/79983685