需求分析:针对Videoservice接口实现日志打印
三个核心包:
spring-aop:AOP核心功能,例如代理⼯⼚
aspectjweaver:简单理解,⽀持切⼊点表达式
aspectjrt:简单理解,⽀持aop相关注解
添加依赖,其他依赖包含在spring-context、spring-core中,不需要额外添加
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
定义service接口和实现类
VideoService接口:
import net.xdclass.sp.domain.Video;
public interface VideoService {
int save(Video video);
Video findById(int id);
}
VideoService实现类:
import net.xdclass.sp.domain.Video;
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();
}
}
定义横切关注点
TimeHandler类:
import java.time.LocalDateTime;
//横切关注点
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());
}
}
添加schema
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"
配置bean和aop
<bean id="timeHandler" class="net.xdclass.sp.aop.TimeHandler"/>
<bean id="videoService" class="net.xdclass.sp.service.VideoServiceImpl"/>
<aop:config>
<!--横切关注点-->
<aop:aspect id="timeAspect" ref="timeHandler">
<!--定义切入点表达式-->
<aop:pointcut id="allMethodLogPointCut" expression="execution(* net.xdclass.sp.service.VideoService.*(..))"/>
<!--配置前置通知和后置通知-->
<aop:before method="printBefore" pointcut-ref="allMethodLogPointCut"/>
<aop:after method="printAfter" pointcut-ref="allMethodLogPointCut"/>
</aop:aspect>
</aop:config>
运行主类测试:
public class App {
public static void main(String [] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
VideoService videoService = (VideoService)context.getBean("videoService");
videoService.save(new Video());
videoService.findById(33);
}
}
定义一个横切关注点(对方法拦截后的处理,前置后置通知),在applicationContext.xml中配置bean(横切关注点的类和service实现类),配置aop(横切关注点下定义切入点表达式、配置前置通知和后置通知)