一、 基于AspectJ的注解实现AOP操作
1.1 导入Spring基本JAR包
1.2 创建被增强类和增强类
- 被增强类Book,实例注解方式创建Book Bean
package com.spring.annotationAOP;
import org.springframework.stereotype.Component;
@Component("book")
public class Book {
public void add(){
System.out.println("book add...");
}
}
增强类Mybook,实例注解方式创建Book Bean
在增强类上需要添加@Aspect注解
- 在增强的方法上需要添加下面五种注解声明通知方法
- @Before – 前置增强
- @Before – 后置增强
- @AfterReturning – 后置增强
- @AfterThrowing –抛出异常后增加
- @Around –前后增强
package com.spring.annotationAOP;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("myBook")
@Aspect
public class Mybook {
@Autowired
private Book book;
@After("execution(* com.spring.annotationAOP.Book.*(..))")
//使用注解方式,表达式添加切入点
public void afterAdd(){
System.out.println("mybook add...");
}
}
1.3 配置Spring核心文件bean3.xml
- 需要开启AOP自动代理
- 需要添加相应的schema约束(aop,context)
<?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"> <!-- bean definitions here -->
<!-- 开启注解扫描,在包里面扫描类、方法、属性上面是否有注解 -->
<context:component-scan base-package="com.spring.annotationAOP"></context:component-scan>
<!-- 开启AOP自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
1.4 测试代码
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.annotationAOP.Book;
public class AOPannotationTest {
@Test
public void testAopAnnotation(){
ApplicationContext context = new ClassPathXmlApplicationContext("aopAnnotation.xml");
Book book = (Book) context.getBean("book");
book.add();
}
}
1.5 输出结果
book add...
mybook add...