文章目录
AOP(面向切面)
1.代理模式
因为aop的底层机制是动态代理,所以我们先来聊一聊代理模式
定义:
为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。代理模式提供了对目标对象的间接访问方式,即通过代理访问目标对象。我们现实生活中像代理律师,房产中介等就是代理模式的体现。
两种代理模式:
- 静态代理
- 动态代理
<1.实现静态代理
以租房为例,代理模式需要四个角色:
- 抽象角色------一般用接口实现------所有要出租房子的房东
- 真实角色-----继承抽象角色接口------具体的一个房东,被代理的角色
- 代理角色------代理真实角色------房产中介
- 客户
代码实现:
(1.总接口
public interface Rent {
//出租房
void rent();
}
(2.真实对象
//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东1要出租房子");
}
}
(3.代理对象
//房屋中介--代理
public class Proxy implements Rent {
//房东
private Host host;
public void setHost(Host host) {
this.host = host;
}
public void rent() {
lookHouse();
host.rent();
fare();
}
private void lookHouse(){
System.out.println("中介带你去看房");
}
private void fare(){
System.out.println("收取中介费");
}
}
(4.测试
public class You {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy();
proxy.setHost(host);
proxy.rent();
}
}
<2.实现动态代理
静态代理是在开始就将接口、实现类、代理类全部都写好,但是我们的真实角色特别多,随之需要的代理也特别多,我们再这样就会工作量特别大,而且有很多重复代码,浪费时间和空间。这个时候我们就可以采用动态代理,动态代理可以动态的生成代理对象。
动态代理需要的角色和静态代理一样
了解并掌握:
InvocationHandler----由代理实例的调用处理程序实现的接口 。
invoke(Object proxy, 方法 method, Object[] args)---- 处理代理实例上的方法调用并返回结果。
Proxy----提供了创建动态代理类和实例的静态方法,它也是由这些方法创建的所有动态代理类的超类。
newProxyInstance(ClassLoader loader, 类<?>[] interfaces, InvocationHandler h) ----返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。
代码实现:
(1.接口:
public interface Rent {
//租房
void rent();
}
(2.真实对象
public class HostOne implements Rent {
public void rent() {
System.out.println("房东1要出租房子");
}
}
public class HostOne implements Rent {
public void rent() {
System.out.println("房东1要出租房子");
}
}
(3.动态代理类生成的接口对象;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class InvocationHandlerProxy implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//动态生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),
this);
}
//proxy:代理类
//method :代理类的调用处理程序的方法 的对象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
lookHouse();
Object result = method.invoke(rent, args);
zhongJieFei();
return result;
}
private void lookHouse(){
System.out.println("中介带你去看房子");
}
private void zhongJieFei(){
System.out.println("收中介费");
}
}
(4.测试
public class Test {
public static void main(String[] args) {
HostOne hostOne = new HostOne();
HostTwo hostTwo = new HostTwo();
InvocationHandlerProxy ihp = new InvocationHandlerProxy();
ihp.setRent(hostOne );
Rent proxy1 = (Rent) ihp.getProxy();
proxy1.rent();
System.out.println("==================================================");
ihp.setRent(hostTwo);
Rent proxy2 = (Rent) ihp.getProxy();
proxy2.rent();
}
}
(5.运行结果
2.AOP
【概述】
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。[百度百科]
那么什么是面向切面编程呢?
我们在编程的时候要尽量做到低耦合、高内聚,所以我们会把项目分为很多模块,什么pojo层、dao层、services层等等,然后在这些层里还会继续分,我们在分的时候,就会发现有很多通用的模块,像日志、事务还有安全等等。它们并不是功能需求,但是很多业务模块都需要。那么我们应该怎么去处理他们呢?大家肯定会想,用接口嘛,给这些模块写一个通用的接口,等我们需要的时候去调用就可以了,这样做确实没问题,但是你去写了之后,会发现有很多重复的代码,看起来超级不爽且麻烦,
给你们举个例子,我们去图书馆要验证身份,然后才能进去,进去之后看书,借书,自习或者去借个厕所。
如下图
我们会发现这个验证身份的模块是重复的,假设我们要用代码去实现,那我们就要给每一个业务类都要加上验证身份的代码(或者继承我们写的接口等),不管是借书、自习、找人等等,给每一个都要加上验证身份的这个模块,写一下就知道,很多重复代码,特别烦。
所以我们就在想,能不能把验证身份这个模块抽出来,不把它放在主流程里:
就是说,我们另找一个地方,把验证身份的代码写上,然后告诉spring,不管是借书也好,借厕所也好,都需要验证身份,你去给我把这个模块插进去(动态的插入,实现非功能模块的重复利用),也就是说我们将日志这些代码和业务代码隔离开,这样的话,我们在写程序的时候,就只要去考虑主流程,不需要去管那些非功能需求的流程。假如我们将这些业务层,看成一层一层的累积起来的蛋糕,那么这些编程日志、事务等像不像一个切面,如果我们可以让这些切面和业务层独立,并且又可以灵活的把它们插入到业务模块里,那我们就实现了AOP。
AOP的几个核心知识点:
- 切面(aspect)----类是对物体特征的抽象,切面就是对横切关注点的抽象
- 连接点(joinpoint)----被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器
- 切入点(pointcut)----对连接点进行拦截的定义
- 通知(advice)----所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
- 目标对象----代理的目标对象
- 织入(weave)----将切面应用到目标对象并导致代理对象创建的过程
- 引入(introduction)----在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段
- 代理(Proxy)----向目标对象应用通知之后创建的对象。
【代码实现】
<1.使用SpringAPI实现AOP
导入aop的织入包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
编写业务类
接口
package priv.sehun.service;
public interface UserService {
void add();
void delete();
void update();
void query();
}
实现类
package priv.sehun.service;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void query() {
System.out.println("查询了一个用户");
}
}
编写日志增加类
package priv.sehun.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//objects:要被调用的方法的参数
//o:目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
package priv.sehun.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue : 返回值
//method : 被调用的方法
//args : 被调用的方法对象的参数
//target : 被调用的目标对象
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+target.getClass().getName()
+"的"+method.getName()+"方法"
+" 返回值为"+returnValue);
}
}
编写Spring核心配置文件
applicationContext.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: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-->
<bean id="userService" class="priv.sehun.service.UserServiceImpl"/>
<!--注册日志类的bean-->
<bean id="log" class="priv.sehun.log.Log"/>
<bean id="afterlog" class="priv.sehun.log.AfterLog"/>
<!--用AOP切入-->
<aop:config>
<!--
切入点
expression表达式,表示要切入的位置
语法:execution([类的修饰符] [类的全路径] [方法] [参数])
-->
<aop:pointcut id="cut" expression="execution(* priv.sehun.service.UserServiceImpl.*(..))"/>
<!--执行通知,增强-->
<aop:advisor advice-ref="log" pointcut-ref="cut"/>
<aop:advisor advice-ref="afterlog" pointcut-ref="cut"/>
</aop:config>
</beans>
测试类
package priv.sehun.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAOPTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.delete();
userService.update();
}
}
运行结果
项目结构
<2.使用注解实现AOP
业务类(目标对象)不变
编写增强器的类
package priv.sehun.anno;
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 Anno {
@Before("execution(* priv.sehun.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=========================before=========================");
}
@After("execution(* priv.sehun.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("*************************after**************************");
}
/* //环绕增加
//切入点参数 : ProceedingJoinPoint
@Around("execution(* priv.sehun.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());//获得执行的切入点
//执行目标方法
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed); //null
}*/
}
编写配置文件
<!--注解实现AOP的类-->
<bean id="anno" class="priv.sehun.anno.Anno"/>
<!--识别注解,自动代理-->
<aop:aspectj-autoproxy/>
测试类
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("annoApplicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
userService.query();
}
运行结果
< 3.自定义类实现AOP
目标对象不变
编写增强类
package priv.sehun.ud;
public class Ud {
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-->
<bean id="userService" class="priv.sehun.service.UserServiceImpl"/>
<!--注册日志类的bean-->
<bean id="log" class="priv.sehun.log.Log"/>
<bean id="afterlog" class="priv.sehun.log.AfterLog"/>
<!--注入AOP增强类-->
<bean id="diy" class="priv.sehun.ud.Ud"/>
<!--编写aop配置文件-->
<aop:config>
<!--切面-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="diyPointCut" expression="execution(* priv.sehun.service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="diyPointCut"/>
<aop:after method="after" pointcut-ref="diyPointCut"/>
</aop:aspect>
</aop:config>
</beans>
测试类
@Test
public void test3(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}