一、AOP概述
AOP,面向切面编程,在进行面向切面编程之前,需要我们先搞清楚下面几个概念:
- 通知(Advice):切面的工作叫通知(定义了切面是什么以及何时使用)。
- 切点(PointCut):定义了切面在何处使用。
- 切面(Aspect):通知(Advice) + 切面(PointCut)
二、引入AOP依赖
<!--Spring AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
三、AOP编程步骤
1. 编写切面类
package cool.gjh.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 切面
* <p>
* 驾驶提醒类
* </p>
*
* @author ACE_GJH
*/
@Aspect
@Component
public class DrivingNotes {
@Pointcut("execution(public void cool.gjh.beans..*.drive())")
public void driveSafety(){};
@Before("driveSafety()")
public void beforeDrive(){
System.out.println("出发前:注意安全");
}
@After("driveSafety()")
public void afterDrive(){
System.out.println("停车后:停放好车辆");
}
}
注意事项:
- 切面 = 通知 + 切点
- 切面类需要成为Bean
2. 配置类开启AspectJ自动代理
在配置类上添加注解@EnableAspectJAutoProxy
package cool.gjh.config;
import cool.gjh.zoo.Animal;
import cool.gjh.zoo.ZooFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* Spring配置类
*
* @author ACE_GJH
*/
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "cool.gjh")
@Configuration
public class Config {
@Bean(name = "singleDog")
public Animal dog(){
return ZooFactory.getAnimalByName("Dog");
}
@Bean
public Animal cat(){
return ZooFactory.getAnimalByName("Cat");
}
}
3. 编写测试类进行测试
package test.cool.gjh.spring;
import cool.gjh.beans.Car;
import cool.gjh.config.Config;
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(classes = Config.class)
public class SpringDITest {
@Autowired
private Car car;
/**
* 测试依赖注入
*/
@Test
public void testInject(){
car.drive();
}
}
测试结果: