首页 > 编程语言 > 详细

3.4 springAOP Helloworld程序

时间:2020-10-14 09:38:53      阅读:29      评论:0      收藏:0      [点我收藏+]

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

我们写一个简单的AOP的Hellowrld程序,这里我们采用前置通知作为案例。

我们准备一个业务类BookService,添加一个SaveBook的方法:

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Component
 7 public class BookService {
 8     public void saveBook(String title){
 9         System.out.println("保存图书:"+title);
10     }
11 }

定义一个Aspect类,在其中定义一个前置通知:

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Component //将当前bean交给spring管理
 7 @Aspect //定义为一个AspectBean
 8 public class DkAspect {
 9     //定义一个前置通知
10     @Before("execution(* com.st.dk.demo7.service.BookService.saveBook(..))")
11     public void befor(){
12         System.out.println("---前置通知---");
13     }
14 }

注意:@Aspect注解本身是没有通知spring 加载当前Bean的功能,所以如果我们希望@Aspect注解的类被Spring加载就需要通过其他方式通知spring加载当前Bean,我们这里使用的是注解@Component.

添加配置类,在配置类中开启对@Aspect的支持:

 1 /**
 2  * @author 戴着假发的程序员
 3  * 
 4  * @description
 5  */
 6 @Configuration
 7 @ComponentScan("com.st.dk.demo7")
 8 @EnableAspectJAutoProxy //开启@AspectJ 支持
 9 public class Appconfig {
10 }

测试:

1 @Test
2 public void testAopHellowrold(){
3     ApplicationContext ac =
4             new AnnotationConfigApplicationContext(Appconfig.class);
5     BookService bean = ac.getBean(BookService.class);
6     bean.saveBook("论一个假发程序员的修养");
7 }

结果:

技术分享图片

我们会发现在执行业务方法之前首先执行了前置通知的代码。 说明前置通知完成。

下一章我们来分析HelloWorld程序。

3.4 springAOP Helloworld程序

原文:https://www.cnblogs.com/jiafa/p/13812732.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!