3.4 springAOP Helloworld程序

戴着假发的程序员出品  抖音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程序。

posted @ 2020-10-14 08:27  戴着假发的程序员0-1  阅读(161)  评论(0编辑  收藏  举报