一、AOP是一种面向切面的编程思想
二、spring aop 优点:
1. 减少重复的代码
2. 提供开发的效率
3. 维护方便
三、spring aop 有五种通知类型
AOP配置文件方式的入门
创建maven项目,坐标依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--AOP联盟-->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!--Spring Aspects-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--aspectj-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.3</version>
</dependency>
</dependencies>
创建被增强的类
// 被增强的类
public class User {
//连接点/切入点
public void add(){
System.out.println("add......");
}
public void update(){
System.out.println("update......");
}
}
将目标类配置到Spring中
<bean id="user" class="com.aopImpl.User"></bean>
定义切面类
public class UserProxy {
//增强/通知 ---》前置通知
public void before(){
System.out.println("before.............");
}
}
在配置文件中定义切面类
<bean id="userProxy" class="com.aopImpl.UserProxy"></bean>
在配置文件中完成aop的配置
<!--配置切面-->
<aop:config>
<!--配置切面 = 切入点 + 通知组成-->
<aop:aspect ref="userProxy">
<!--前置通知:UserServiceImpl的save方法执行前,会增强-->
<!--pointcut:后边是切入点表达式,作用是知道对对面的那个方法进行增强-->
<aop:before method="before" pointcut="execution(public void com.aopImpl.User.add())"/>
</aop:aspect>
</aop:config>
完成测试
public class DemoTest {
@Test
public void aopTest1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) applicationContext.getBean("user");
user.add();
}
}