注解的类型
通知的配置语法:@通知注解("切点表达式")
- 前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行
- 后置通知 @AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行
- 环绕通知 @Around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行
- 异常抛出通知 @AfterThrowing 用于配置异常抛出通知。指定增强的方法在出现异常时执行
- 最终通知 @After 用于配置最终通知。无论增强方式执行是否有异常都会执行
注解AOP的开发步骤测试
① 使用@Aspect标注切面类
② 使用@通知注解标注通知方法
③ 在配置文件中配置aop自动代理<aop:aspectj-autoproxy/>
1、目标对象接口与实现接口类
public interface targetInterface {
void save();
void delete();
}
@Component("target")
public class target implements targetInterface {
@Override
public void save() {
System.out.println("目标对象的功能save执行.....");
}
@Override
public void delete() {
System.out.println("目标对象的功能delete执行.....");
}
}
2、切面类
//切面类
@Component("myAspect")
@Aspect
public class myAspect {
@Before("execution(public void com.hlc.aop.target.save())")
public void before(){
System.out.println("前置增强....");
}
@AfterReturning("execution(public void com.hlc.aop.target.delete())")
public void after(){
System.out.println("后置增强....");
}
@After("execution(public void com.hlc.aop.target.delete())")
public void bye(){
System.out.println("增强结束....");
}
@Around("execution(public void com.hlc.aop.target.save())")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕保护进程....");
Object proceed = proceedingJoinPoint.proceed();
System.out.println("运行完毕!保护结束....");
return proceed;
}
}
3、xml配置AOP自动代理与组件扫描
<!-- aop的自动代理,通常结合组件扫描context一起使用于aop的注解开发-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<context:component-scan base-package="com.hlc.aop"/>
</beans>
4、测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-aop.xml")
public class aopTest {
@Autowired
private targetInterface target;
@Test
public void test1(){
target.save();
}
@Test
public void test2(){
target.delete();
}
}
5、测试结果
在前面我们对于springIOC的DI注入的学习过程中,关于xml文件的标签属性特点有了很深的记忆性,注解肯定是好用的。