面向切面(儿)编程(横切编程)

  1. Spring 核心功能之一
    • Spring 利用AspectJ 实现.
  2. 底层是利用 反射的动态代理机制实现的
  3. 其好处: 在不改变原有功能情况下, 为软件扩展(织入)横切功能

生活中的横切功能事例:

02 - Unit011:Spring AOP

软件中的横切编程需求:

02 - Unit011:Spring AOP

AOP其原理如下:

02 - Unit011:Spring AOP

切面组件

是封装横切功能的Bean组件, 用于封装扩展功能方法.

AOP配置步骤

1.引入aspectj包

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.5.4</version>
</dependency>

2.创建切面组件对象:

@Component //将当前类纳入容器管理
@Aspect //Aspect 切面(儿), 声明当前的bean是
// 一个切面(儿)组件!
public class DemoAspect implements Serializable{
    //@Before 在方法执行之前执行
    //userService 的所有方法
    @Before("bean(userService)")
    public void test(){
        System.out.println("Hello World!");
    }

}   

3.配置AOP功能 resource/conf/spring-aop.xml:

<?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:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    <!-- 开启组件扫描 -->
    <context:component-scan 
        base-package="cn.tedu.cloudnote.aop"/>
    <!-- 开启aop, 底层使用aspectj -->
    <aop:aspectj-autoproxy/>    

</beans>     
spring-aop.xml

相关文章:

  • 2021-09-19
  • 2021-07-01
  • 2021-12-02
猜你喜欢
  • 2021-11-25
  • 2021-06-13
  • 2021-08-19
  • 2023-01-24
  • 2021-12-15
  • 2022-12-23
  • 2021-08-20
相关资源
相似解决方案