一、Spring配置文件
<!--通过@AspectJ注解的形式来使用Spring AOP,强制使用CGLIB代理--> <aop:aspectj-autoproxy proxy-target-class="true"/>
上面这个配置的目的是告知Spring,我们将使用Annotation注解(比如:@Aspect、@Before、@After、@AfterReturning等)的方式来使用Spring AOP。
二、定义方面类(aspect)
package aop; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; /** * 定义一个方面(Aspect),Maven需要引用spring-aspects * 这个方面(Aspect)包括了多个增加处理(通知,比如:前置、后置、后置返回、异常等) * * @author xfyou * @date 2018/9/29 */ @Aspect @Component public class Advice { @Before(value = "execution(* bean.*.*(..)) && args(arg0)", argNames = "arg0") public void beforeAdvice(String arg0) { System.out.println("arg0=" + arg0); } @AfterReturning(pointcut = "execution(* bean.*.*(..))", returning = "retVal") public void afterReturnAdvice(String retVal) { System.out.println("fristName=" + retVal); } @AfterThrowing(pointcut = "execution(* bean.*.*(..))", throwing = "ex") public void afterThrowingAdvice(Exception ex) { System.err.println(ex.getMessage()); } }
上面分别定义了三个“前置”、“后置返回”、“异常”增强处理(或者叫着:通知)方法。通过@Aspect标注的Advice类必须注册到Spring容器中才能使用,所以我们这里使用到了一个@Component注解让Spring能够自动扫描并注册到Spring容器中。
三、测试
package bean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author xfyou * @date 2018/9/6 */ public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml"); Person person = context.getBean(Person.class); person.setFirstName("frank"); person.getFirstName(); person.test(); } }
输出如下:
beforeAdvice,arg0=frank afterReturnAdvice,retVal=frank afterThrowingAdvice,exception:RuntimeException Exception in thread "main" java.lang.RuntimeException: RuntimeException at bean.Person.test(Person.java:18) at bean.Person$$FastClassBySpringCGLIB$$40dc9373.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)