aop注解实现
- spring配置文件
- 目标接口,目标实现类,切面类 注解写法
- 使用spring-test测试
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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- spring 组件扫描 --><context:component-scan base-package="com.lovely.aop.anno"/><!-- aop 自动代理测试 --><aop:aspectj-autoproxy/></beans>
目标接口,目标实现类,切面类 注解写法
package com.lovely.aop.anno;public interface TargetInterface {public abstract void save();
}
package com.lovely.aop.anno;import org.springframework.stereotype.Component;@Component("target")
public class Target implements TargetInterface {public void save() {System.out.println("save running about aop...");}
}
package com.lovely.aop.anno;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component("myAspect")
@Aspect
public class MyAspect {@Before(value = "execution(* com.lovely.aop.anno.*.*(..))")public void before() {System.out.println("前置增强...");}public void afterReturning() {System.out.println("后置增强...");}@Around("MyAspect.myPoint()")public Object around(ProceedingJoinPoint process) {System.out.println("环绕通知前...");Object obj = null;try {obj = process.proceed();} catch (Throwable throwable) {throwable.printStackTrace();}System.out.println("环绕通知后...");return obj;}public void afterThrowing() {System.out.println("异常拉...");}@After("myPoint()")public void after() {System.out.println("最终通知...");}@Pointcut("execution(* com.lovely.aop.anno.Target.*(..))")public void myPoint() {}}
使用spring-test测试
import com.lovely.aop.anno.TargetInterface;
import org.junit.Test;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContextAnno.xml")
public class AopAnnotationTest {@Autowiredprivate TargetInterface target;@Testpublic void test1() {target.save();}}