基于注解的AOP开发
1. 创建接口和目标类(内部有切点)
package com.sjj.anno;
public interface TargetInterface {
public void print_hello();
}
package com.sjj.anno;
import org.springframework.stereotype.Component;
@Component("target") // 交予spring
public class Target implements TargetInterface {
@Override
public void print_hello() {
System.out.println("HHHHHello");
}
}
2. 创建切面类(内部有增强方法)
package com.sjj.anno;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect // 声明切面类
@Component("myAspect") // 交予spring
public class MyAspect {
@Before("execution(* com.sjj.anno.*.*(..))")
public void before(){
System.out.println("=====前置增强=====");
}
}
3. 将目标类和切面类的对象创建权交给spring
// Component注解
4. 在切面类中使用注解配置织入关系
// Aspect注解和通知方法注解(Before之类的)
5. 在配置文件中开启组件扫描和AOP自动代理
<!--组件扫描-->
<context:component-scan base-package="com.sjj.anno" />
<!--aop自动代理-->
<aop:aspectj-autoproxy/>
6. 测试
package com.sjj.anno;
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:appContext-anno.xml")
public class AnnoTest {
@Autowired
private TargetInterface target;
@Test
public void test_anno01(){
target.print_hello();
}
}
注解解析
注解通知的类型
| 名称 |
注解 |
说明 |
| 前置 |
@Before |
切入点方法之前 |
| 后置 |
@AfterReturning |
切入点方法之后 |
| 环绕 |
@Around |
切入点方法前后都执行 |
| 异常抛出 |
@Throwing |
出现异常时执行 |
| 最终 |
@After |
最终通知,无论是否有异常都执行 |