1.三个核心包
1.1spring-aop:AOP核心功能,例如代理工厂(已存在包含在下面这个包里)
1.2aspectjweaver:简单理解,支持切入点表达式
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
1.3aspectjrt:简单理解,支持aop相关注解(被上边的包包含)
2.定义service接口和实现类
接口:VideoService
public interface VideoService {
int save(Video video);
Video findById(int id);
}
实现类:VideoServiceImpl
public class VideoServiceImpl implements VideoService {
public int save(Video video) {
System.out.println("保存Video");
return 1;
}
public Video findById(int id) {
System.out.println("根据id找视频");
return new Video();
}
}
3.定义横切关注点
public class TimeHandler {
public void printBefore(){
System.out.println("printBefore 日志 time ="+ LocalDateTime.now().toString());
}
public void printAfter(){
System.out.println("printAfter 日志 time ="+ LocalDateTime.now().toString());
}
}
4.在applicationContex.xmlt添加schema
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
xmlns:aop="http://www.springframework.org/schema/aop"
>
5.配置bean和aop
<bean id="timehandler" class="work.yspan.sp.aop.TimeHandler"/>
<bean id="videoService" class="work.yspan.sp.service.VideoServiceImpl"/>
<!--aop配置-->
<aop:config>
<!--横切关注点-->
<aop:aspect id="timeAspect" ref="timehandler">
<!--定义切入点表达式-->
<aop:pointcut id="allMethodPointCut" expression="execution(* work.yspan.sp.service.VideoService.*(..))"/>
<!--<aop:pointcut id="allMethodPointCut" expression="execution(* work.yspan.sp.service.VideoService.sav*(..))"/>-->
<!--配置前置通知后置通知-->
<aop:before method="printBefore" pointcut-ref="allMethodPointCut"/>
<aop:after method="printAfter" pointcut-ref="allMethodPointCut"/>
</aop:aspect>
</aop:config>
6.测试代码
public static void main(String[] args){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
testaop(applicationContext);
}
private static void testaop(ApplicationContext applicationContext){
VideoService videoService=(VideoService)applicationContext.getBean("videoService");
videoService.save(new Video());
videoService.findById(263);
}
测试效果截图:
7.改变aop配置 pointcut 的expression
效果截图:(只切入了Video)