已解决
Spring-AOP+入门案例(注解)+AOP切入点语法+AOP通知类型
来自网友在路上 175875提问 提问时间:2023-09-26 13:26:54阅读次数: 75
最佳答案 问答题库758位专家为你答疑解惑
一、简介+工作流程。
简介
SpringAop实际上就是代理模式
切面=切入点+连接点+通知
工作流程
二、导入依赖
1.spring-aop包
该包是在spring-context依赖下的子包,所以有context就有aop
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.10.RELEASE</version></dependency>
2.aspectjweaver包
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency>
三、定义接口和实现类
public interface BookDao {public void save();public void update();
}
tip:@Repository 注解加在Dao层上,也就是与数据库操作的层上。
@Repository
public class BookDaoImpl implements BookDao {public void save() {System.out.println(System.currentTimeMillis());System.out.println("book dao save ...");}public void update(){System.out.println("book dao update ...");}
}
四、定义通知类+制作通知+定义切入点
@Component //告诉spring要把MyAdvice 当作Bean
//设置当前类为切面类类
@Aspect //告诉spring要把MyAdvice 当作AOP,切面类
//定义通知类
public class MyAdvice {//设置切入点,要求配置在方法上方@Pointcut("execution(void com.itheima.dao.BookDao.update())")private void pt(){}//设置在切入点pt()的前面运行当前操作(前置通知)@Before("pt()")//制作共性通知public void method(){System.out.println(System.currentTimeMillis());}
}
由图可知,@Aspect 是告诉spring这是一个aop,@Pointcut 代表 pt()方法是一个切入点,注意py()方法只需要一个空架子 然后@Before(“pt()”) 代表在pt()方法之前将共性方法切入进去。
五、在spring核心配置中开启注解式aop的功能
@Configuration
@ComponentScan("com.itheima")
//开启注解开发AOP功能
@EnableAspectJAutoProxy
public class SpringConfig {
}
六、自定义service层调用测试
public class App {public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);
// bookDao.update();bookDao.update();
// System.out.println(bookDao.getClass());}j
}
七、切入点详解
切入点表达式语法规格:
切入点表达式书写技巧:
八、AOP通知类型
1.@After----在切入点之后
2.@Before----在切入点之前
3.@Around----在切入点周围
ProceedingJoinPoint是用来获取原方法的对象,并且返回的是原方法的返回值
4.@AfterReturning
5.@AfterThrowing
查看全文
99%的人还看了
猜你感兴趣
版权申明
本文"Spring-AOP+入门案例(注解)+AOP切入点语法+AOP通知类型":http://eshow365.cn/6-13981-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: Unity添加自定义菜单按钮
- 下一篇: WebGL绘制圆形的点