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

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

AOP 面向切面编程

AOP aspect oriented programming

OOP Object oriented programming

  1. 提供申明式服务
  2. 允许用户实现自定义切面

传统编程模式

自上而下,纵向的编程

Jsp
    ->
Action
    ->
Service
    ->
Dao

AOP 编程:

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

Jsp

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

好处:

  1. 使得真实角色处理业务更加纯粹,不再关注公共的问题
  2. 公共业务由代理类完成,实现业务的分工
  3. 公共业务发生扩展时变得更加集中和方便


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

切面 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--

总结

公共业务:

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

分离思想

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

            </div>
目录
相关文章
|
3天前
|
安全 Java 调度
Java编程时多线程操作单核服务器可以不加锁吗?
Java编程时多线程操作单核服务器可以不加锁吗?
16 2
|
7天前
|
Java
死磕-java并发编程技术(二)
死磕-java并发编程技术(二)
|
7天前
|
存储 Java 调度
死磕-java并发编程技术(一)
死磕-java并发编程技术(一)
|
7天前
|
设计模式 缓存 Java
死磕-高效的Java编程(一)
死磕-高效的Java编程(一)
|
7天前
|
算法 安全 Java
JAVA并发编程系列(12)ThreadLocal就是这么简单|建议收藏
很多人都以为TreadLocal很难很深奥,尤其被问到ThreadLocal数据结构、以及如何发生的内存泄漏问题,候选人容易谈虎色变。 日常大家用这个的很少,甚至很多近10年资深研发人员,都没有用过ThreadLocal。本文由浅入深、并且才有通俗易懂方式全面分析ThreadLocal的应用场景、数据结构、内存泄漏问题。降低大家学习啃骨头的心理压力,希望可以帮助大家彻底掌握并应用这个核心技术到工作当中。
|
7天前
|
Java 程序员 编译器
死磕-高效的Java编程(二)
死磕-高效的Java编程(二)
|
2天前
|
Java
JAVA并发编程系列(13)Future、FutureTask异步小王子
本文详细解析了Future及其相关类FutureTask的工作原理与应用场景。首先介绍了Future的基本概念和接口方法,强调其异步计算特性。接着通过FutureTask实现了一个模拟外卖订单处理的示例,展示了如何并发查询外卖信息并汇总结果。最后深入分析了FutureTask的源码,包括其内部状态转换机制及关键方法的实现原理。通过本文,读者可以全面理解Future在并发编程中的作用及其实现细节。
|
5天前
|
Java 数据处理 调度
Java中的多线程编程:从基础到实践
本文深入探讨了Java中多线程编程的基本概念、实现方式及其在实际项目中的应用。首先,我们将了解什么是线程以及为何需要多线程编程。接着,文章将详细介绍如何在Java中创建和管理线程,包括继承Thread类、实现Runnable接口以及使用Executor框架等方法。此外,我们还将讨论线程同步和通信的问题,如互斥锁、信号量、条件变量等。最后,通过具体的示例展示了如何在实际项目中有效地利用多线程提高程序的性能和响应能力。
|
6天前
|
安全 算法 Java
Java中的多线程编程:从基础到高级应用
本文深入探讨了Java中的多线程编程,从最基础的概念入手,逐步引导读者了解并掌握多线程开发的核心技术。无论是初学者还是有一定经验的开发者,都能从中获益。通过实例和代码示例,本文详细讲解了线程的创建与管理、同步与锁机制、线程间通信以及高级并发工具等主题。此外,还讨论了多线程编程中常见的问题及其解决方案,帮助读者编写出高效、安全的多线程应用程序。
|
8天前
|
存储 缓存 Java
JAVA并发编程系列(11)线程池底层原理架构剖析
本文详细解析了Java线程池的核心参数及其意义,包括核心线程数量(corePoolSize)、最大线程数量(maximumPoolSize)、线程空闲时间(keepAliveTime)、任务存储队列(workQueue)、线程工厂(threadFactory)及拒绝策略(handler)。此外,还介绍了四种常见的线程池:可缓存线程池(newCachedThreadPool)、定时调度线程池(newScheduledThreadPool)、单线程池(newSingleThreadExecutor)及固定长度线程池(newFixedThreadPool)。