JAVA入门[14]-Spring MVC AOP

简介:


一、基本概念

1.AOP简介

DI能够让相互协作的软件组件保持松散耦合;而面向切面编程(aspect-oriented programming,AOP)允许你把遍布应用各处的功能分离出来形成可重用的组件。把这些横切关注点与业务逻辑相分离正是面向切面编程(AOP)所要解决的问题

常见场景:日志、安全、事物、缓存

Image(2)

2.AOP用到的一些术语

项目中每个模块的核心功能都是为特定业务领域提供服务,但是这些模块都需要类似的辅助功能,例如安全和事务管理,这时候需要引入AOP的概念。

Image(3)

通知定义了切面是什么以及何时使用, Spring切面可以应用5种类型的通知:

  • 前置通知(Before):在目标方法被调用之前调用通知功能;
  • 后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出是什么;
  • 返回通知(After-returning):在目标方法成功执行之后调用通知;
  • 异常通知(After-throwing):在目标方法抛出异常后调用通知;
  • 环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。

连接点(join potint)是在应用执行过程中能够插入切面的一个点。这个点可以是调用方法时、抛出异常时、甚至修改一个字段时。切面代码可以利用这些点插入到应用的正常流程之中,并添加新的行为

切点(poincut)的定义会匹配通知所要织入的一个或多个连接点。我们通常使用明确的类和方法名称,或是利用正则表达式定义所匹配的类和方法名称来指定这些切点

 

二、准备service模块

1.service bean

1
2
3
4
5
6
7
8
9
10
11
public  class  CategoryService1 {
     public  void  add( int  id) {
         System.out.println( "CategoryService1.add()" );
     }
}
 
public  class  CategoryService2{
     public  void  add( int  id) {
         System.out.println( "CategoryService2.add()" );
     }
}

2.配置bean

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version= "1.0"  encoding= "UTF-8" ?>
<beans xmlns= "http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop= "http://www.springframework.org/schema/aop"
xmlns:tx= "http://www.springframework.org/schema/tx"
xsi:schemaLocation="http: //www.springframework.org/schema/beans
         http: //www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http: //www.springframework.org/schema/aop
         http: //www.springframework.org/schema/aop/spring-aop-4.2.xsd">
 
<bean id= "categoryServiceImpl"  class = "service.CategoryService1" ></bean>
<bean id= "CategoryServiceImpl2"  class = "service.CategoryService2" ></bean>
</beans>

3.单元测试

1
2
3
4
5
6
7
8
9
10
@Test
public  void  test(){
     ApplicationContext context= new  ClassPathXmlApplicationContext( "aop.xml" );
 
     CategoryService1 service1=context.getBean(CategoryService1. class );
     service1.add( 1 );
 
     CategoryService2 service2=context.getBean(CategoryService2. class );
     service2.add( 2 );
}

运行结果:

CategoryService1.add()

CategoryService2.add()

 

三、XML方式声明AOP

Spring所创建的通知都是用标准的Java类编写的, 定义通知所应用的切点通常会使用注解或在Spring配置文件里采用XML来编写,这两种语法对于Java开发者来说都是相当熟悉的。

注意Spring只支持方法级别的连接点。

切入点表达式

execution指示器是我们在编写切点定义时最主要使用的指示器

Image(4)

 

Demo

我们要实现的一个简单示例是:在service方法调用前和调用后打印日志“write log”。

1
2
3
4
5
public  class  LogHandler {
     public  void  log(){
         System.out.println( "write log." );
     }
}

aop.xml添加配置:

1
2
3
4
5
6
7
8
<bean id= "logHandler"  class = "pointcut.LogHandler" ></bean>
     <aop:config>
         <aop:aspect id= "log"  ref= "logHandler" >
             <aop:pointcut id= "addLog"  expression= "execution(* service.*.*(..))" ></aop:pointcut>
             <aop:before method= "log"  pointcut-ref= "addLog" ></aop:before>
             <aop:after method= "log"  pointcut-ref= "addLog" ></aop:after>
         </aop:aspect>
     </aop:config> 

单元测试:

1
2
3
4
5
6
7
8
9
10
public  class  AopTests {
     @Test
     public  void  test() {
         ApplicationContext context =  new  ClassPathXmlApplicationContext( "aop.xml" );
         CategoryService1 service1 = context.getBean(CategoryService1. class );
         service1.add( 1 );
         CategoryService2 service2 = context.getBean(CategoryService2. class );
         service2.add( 2 );
     }
}

运行报错:

org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException

原来是忘了pom依赖:

1
2
3
4
5
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aspects</artifactId>
     <version>${spring.version}</version>
</dependency> 

运行结果:

write log.

CategoryService1.add()

write log.

write log.

CategoryService2.add()

write log.

  完整的pom.xml

 

四、aop:around

通过使用环绕通知,可以实现前置通知和后置通知所实现的功能,而且只需要在一个方法中实现。

1
2
3
4
5
6
7
8
9
10
11
public  class  LogTimeHandler {
     public  void  log(ProceedingJoinPoint jp)  throws  Throwable {
         try  {
             System.out.println( "1.before log " + new  Date().getTime()); //记录开始时间
             jp.proceed();
             System.out.println( "2.after log " + new  Date().getTime()); //记录结束时间
         } catch  (Exception e){
             System.out.println( "log fail " );
         }
     }
}

  

在aop1.xml中配置aop:round通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version= "1.0"  encoding= "UTF-8" ?>
<beans xmlns= "http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"  xmlns:aop= "http://www.springframework.org/schema/aop"
xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" >
 
     <bean id= "categoryService"  class = "service.CategoryService1" ></bean>
     <bean id= "logHanlder"  class = "pointcut.LogTimeHandler" ></bean>
     <aop:config>
         <aop:aspect id= "log"  ref= "logHanlder" >
             <aop:pointcut id= "addlog"  expression= "execution(* service.*.*(..))" ></aop:pointcut>
             <aop:around method= "log"  pointcut-ref= "addlog" ></aop:around>
         </aop:aspect>
     </aop:config>
</beans>

  

单元测试:

1
2
3
4
5
6
7
8
public  class  AopTest1 {
     @Test
     public  void  test(){
         ApplicationContext context= new  ClassPathXmlApplicationContext( "aop1.xml" );
         CategoryService1 service1=context.getBean(CategoryService1. class );
         service1.add( 1 );
     }
}

运行结果:

1
2
3
1 .before log  1489990832246
CategoryService1.add()
2 .after log  1489990832263

  

五、注解方式创建AOP

定义切面需要给类添加@Aspect注解。然后需要给方法添加注解来声明通知方法,各通知类型对应的注解:

  • @After 通知方法会在目标方法返回或抛出异常后
  • @AfterReturning 通知方法会在目标方法返回后调用
  • @AfterThrowing 通知方法会在目标方法抛出异常后调用
  • @Around 通知方法会将目标方法封装起来
  • @Before 通知方法会在目标方法调用之前执行
1
2
3
4
5
6
7
8
9
@Component
@Aspect
public  class  LogHelper3 {
 
     @Before ( "execution(* service.*.*(..))" )
     public  void  logStart(){
         System.out.println( "log start " + new  Date().getTime());
     }
}

然后定义JavaConfig类,注意需要给类添加@EnableAspectJAutoProxy注解启用自动代理功能。

1
2
3
4
5
@Configuration
@EnableAspectJAutoProxy
@ComponentScan (basePackageClasses = {service.CategoryService3. class ,pointcut.LogHelper3. class })
public  class  BeanConfig {
}

  单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith (SpringJUnit4ClassRunner. class )
@ContextConfiguration (classes = BeanConfig. class )
public  class  AopTest3 {
 
     @Autowired
     CategoryService3 service;
 
     @Test
     public  void  testConfigAop(){
         service.add( 100 );
     }
}

运行结果:

1
2
log start  1489990977264
add category id= 100

  

结尾:

参考:《spring实战》

源码下载:https://github.com/cathychen00/learnjava/tree/master/DemoAOP




    本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/6873732.html,如需转载请自行联系原作者



相关文章
|
5月前
|
存储 Oracle Java
java零基础学习者入门课程
本课程为Java零基础入门教程,涵盖环境搭建、变量、运算符、条件循环、数组及面向对象基础,每讲配示例代码与实践建议,助你循序渐进掌握核心知识,轻松迈入Java编程世界。
438 0
|
5月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
584 3
|
6月前
|
Java
java入门代码示例
本文介绍Java入门基础,包含Hello World、变量类型、条件判断、循环及方法定义等核心语法示例,帮助初学者快速掌握Java编程基本结构与逻辑。
506 0
|
6月前
|
Java API 数据库
2025 年最新 Java 实操学习路线,从入门到高级应用详细指南
2025年Java最新实操学习路线,涵盖从环境搭建到微服务、容器化部署的全流程实战内容,助你掌握Java 21核心特性、Spring Boot 3.2开发、云原生与微服务架构,提升企业级项目开发能力,适合从入门到高级应用的学习需求。
1922 0
|
6月前
|
前端开发 Java 数据库连接
帮助新手快速上手的 JAVA 学习路线最详细版涵盖从入门到进阶的 JAVA 学习路线
本Java学习路线涵盖从基础语法、面向对象、异常处理到高级框架、微服务、JVM调优等内容,适合新手入门到进阶,助力掌握企业级开发技能,快速成为合格Java开发者。
787 3
|
6月前
|
监控 Java API
2025 年全新出炉的 Java 学习路线:从入门起步到实操精通的详细指南
2025年Java学习路线与实操指南,涵盖Java 21核心特性、虚拟线程、Spring Boot 3、微服务、Spring Security、容器化部署等前沿技术,助你从入门到企业级开发进阶。
1286 0
|
7月前
|
NoSQL Java 关系型数据库
Java 从入门到进阶完整学习路线图规划与实战开发最佳实践指南
本文为Java开发者提供从入门到进阶的完整学习路线图,涵盖基础语法、面向对象、数据结构与算法、并发编程、JVM调优、主流框架(如Spring Boot)、数据库操作(MySQL、Redis)、微服务架构及云原生开发等内容,并结合实战案例与最佳实践,助力高效掌握Java核心技术。
756 2
|
7月前
|
Java 测试技术 API
Java IO流(二):文件操作与NIO入门
本文详解Java NIO与传统IO的区别与优势,涵盖Path、Files类、Channel、Buffer、Selector等核心概念,深入讲解文件操作、目录遍历、NIO实战及性能优化技巧,适合处理大文件与高并发场景,助力高效IO编程与面试准备。
|
7月前
|
Java 编译器 API
Java Lambda表达式与函数式编程入门
Lambda表达式是Java 8引入的重要特性,简化了函数式编程的实现方式。它通过简洁的语法替代传统的匿名内部类,使代码更清晰、易读。本文深入讲解Lambda表达式的基本语法、函数式接口、方法引用等核心概念,并结合集合操作、线程处理、事件回调等实战案例,帮助开发者掌握现代Java编程技巧。同时,还解析了面试中高频出现的相关问题,助你深入理解其原理与应用场景。
|
7月前
|
安全 Java 数据库连接
2025 年最新 Java 学习路线图含实操指南助你高效入门 Java 编程掌握核心技能
2025年最新Java学习路线图,涵盖基础环境搭建、核心特性(如密封类、虚拟线程)、模块化开发、响应式编程、主流框架(Spring Boot 3、Spring Security 6)、数据库操作(JPA + Hibernate 6)及微服务实战,助你掌握企业级开发技能。
912 3

热门文章

最新文章