Java学习路线-58:AOP面向切面编程

简介: Java学习路线-58:AOP面向切面编程

AOP 面向切面编程

AOP aspect oriented programming

OOP Object oriented programming


提供申明式服务

允许用户实现自定义切面

传统编程模式


自上而下,纵向的编程


Jsp
    ->
Action
    ->
Service
    ->
Dao

AOP 编程:

在不改变原有的代码,增加新的功能


Jsp
    ->
Action
    ->
Service  <- log()
    ->
Dao

好处:


使得真实角色处理业务更加纯粹,不再关注公共的问题

公共业务由代理类完成,实现业务的分工

公共业务发生扩展时变得更加集中和方便

关注点:日志,安全,缓存,事务

切面 Aspect:一个关注点的模块化


实现 AOP

1、通过 Spring 接口实现


依赖


<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>
package com.spring.service;
public interface UserService {
    public void add();
    public void delete();
}
package com.spring.service.impl;
import com.spring.service.UserService;
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("add");
    }
    @Override
    public void delete() {
        System.out.println("delete");
    }
}
package com.spring.aop;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
// 前置通知
public class BeforeLog implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target)
    throws Throwable {
        System.out.println(target.getClass().getName() + ": "+ method.getName());
    }
}
package com.spring.aop;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
// 后置通知
public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(
        Object result, Method method, Object[] objects, Object target)
        throws Throwable {
        System.out.println(target.getClass().getName() + ": "+ method.getName());
    }
}
<?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="service" class="com.spring.service.impl.UserServiceImpl"/>
    <bean id="beforeLog" class="com.spring.aop.BeforeLog"/>
    <bean id="AfterLog" class="com.spring.aop.AfterLog"/>
    <aop:config>
        <aop:pointcut id="action"
        expression="execution(* com.spring.service.impl.UserServiceImpl.* (..))"/>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="action"/>
        <aop:advisor advice-ref="AfterLog" pointcut-ref="action"/>
    </aop:config>
</beans>
package com.spring.test;
import com.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService service = (UserService) context.getBean("service");
        service.add();
        service.delete();
    }
}

执行结果


com.spring.service.impl.UserServiceImpl: add
add
com.spring.service.impl.UserServiceImpl: add
com.spring.service.impl.UserServiceImpl: delete
delete
com.spring.service.impl.UserServiceImpl: delete

Spring AOP 本质


就是讲公共的业务(如日期,安全等)和领域业务结合,

当执行领域业务时将会把公共业务加进来,

实现公共业务的重复利用,

领域业务更纯粹,可以专注于领域业务,

本质是动态代理


2、自定义类实现 AOP


UserService、UserServiceImpl、Demo 三个类不变


添加 Log 类和修改配置文件


package com.spring.aop;
public class Log {
    public void before(){
        System.out.println("--before--");
    }
    public void after(){
        System.out.println("--after--");
    }
}
<?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="service" class="com.spring.service.impl.UserServiceImpl"/>
    <bean id="log" class="com.spring.aop.Log"/>
    <aop:config>
        <aop:aspect ref="log">
            <aop:pointcut id="action"
            expression="execution(* com.spring.service.impl.UserServiceImpl.* (..))"/>
            <aop:before method="before" pointcut-ref="action"/>
            <aop:after method="after" pointcut-ref="action"/>
        </aop:aspect>
    </aop:config>
</beans>

执行结果


--before--
add
--after--
--before--
delete
--after--

3、注解实现 AOP

业务类不改变


package com.spring.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Log {
    @Before("execution(* com.spring.service.impl.UserServiceImpl.* (..))")
    public void before(){
        System.out.println("--before--");
    }
    @After("execution(* com.spring.service.impl.UserServiceImpl.* (..))")
    public void after(){
        System.out.println("--after--");
    }
    @Around("execution(* com.spring.service.impl.UserServiceImpl.* (..))")
    public Object Around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("--Around before--");
        Object result = pjp.proceed();
        System.out.println("--Around after--");
        return result;
    }
}
<?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="service" class="com.spring.service.impl.UserServiceImpl"/>
    <bean id="log" class="com.spring.aop.Log"/>
    <aop:aspectj-autoproxy />
</beans>

执行结果


--Around before--
--before--
add
--Around after--
--after--
--Around before--
--before--
delete
--Around after--
--after--

总结

公共业务:

日志,安全,权限,缓存,事务


分离思想


在不改变原有代码的情况下,增加额外的功能

相关文章
|
2月前
|
IDE Java 编译器
java编程最基础学习
Java入门需掌握:环境搭建、基础语法、面向对象、数组集合与异常处理。通过实践编写简单程序,逐步深入学习,打牢编程基础。
233 1
|
2月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
178 6
|
3月前
|
SQL Java 数据库
2025 年 Java 从零基础小白到编程高手的详细学习路线攻略
2025年Java学习路线涵盖基础语法、面向对象、数据库、JavaWeb、Spring全家桶、分布式、云原生与高并发技术,结合实战项目与源码分析,助力零基础学员系统掌握Java开发技能,从入门到精通,全面提升竞争力,顺利进阶编程高手。
725 1
|
2月前
|
安全 前端开发 Java
从反射到方法句柄:深入探索Java动态编程的终极解决方案
从反射到方法句柄,Java 动态编程不断演进。方法句柄以强类型、低开销、易优化的特性,解决反射性能差、类型弱、安全性低等问题,结合 `invokedynamic` 成为支撑 Lambda 与动态语言的终极方案。
168 0
|
3月前
|
Java 开发者
Java并发编程:CountDownLatch实战解析
Java并发编程:CountDownLatch实战解析
474 100
|
2月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
3月前
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
278 16
|
3月前
|
NoSQL Java 关系型数据库
超全 Java 学习路线,帮你系统掌握编程的超详细 Java 学习路线
本文为超全Java学习路线,涵盖基础语法、面向对象编程、数据结构与算法、多线程、JVM原理、主流框架(如Spring Boot)、数据库(MySQL、Redis)及项目实战等内容,助力从零基础到企业级开发高手的进阶之路。
350 1
|
3月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
468 0
|
2月前
|
监控 Java Spring
AOP 切面编程
AOP(面向切面编程)通过动态代理在不修改源码的前提下,对方法进行增强。核心概念包括连接点、通知、切入点、切面和目标对象。常用于日志记录、权限校验、性能监控等场景,结合Spring AOP与@Aspect、@Pointcut等注解,实现灵活的横切逻辑管理。
440 6
AOP 切面编程