1.1spring-aop:AOP核心功能,例如代理工厂(已存在包含在下面这个包里)
1.2aspectjweaver:简单理解,支持切入点表达式
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.11version>
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:config>
<aop:aspect id="timeAspect" ref="timehandler">
<aop:pointcut id="allMethodPointCut" expression="execution(* work.yspan.sp.service.VideoService.*(..))"/>
<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);
}
测试效果截图:
效果截图:(只切入了Video)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)