AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
OOP (Object Oriented Programming) 面向对象编程
AOP (Aspect Oritented Programming) 面向切面编程
OOP 到AOP 不是替换的关系,而是一种扩展,使用了AOP后,OOP还是会继续使用
提供声明式事务;允许用户自定义切面
AOP 主要就是在不改变原本代码的前提下,新增功能上去不影响原本的功能。
AOP在Spring中是非常重要的一个功能,可以理解为一个业务就是一条线,当使用一把刀在这条线的指定位置砍下去,添加新的功能到断开处,最后在进行织入,最后连起来成为了一条新的线,新的功能就可以实现。
添加依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.18</version>
</dependency>
修改配置文件
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xs">
<!--注解扫描 默认开启注解支持-->
<context:component-scan base-package="com.bing"/>
<!--
proxy-target-class="true" 如果是true 就是cglib代理 如果是false就是jdk 默认是false
-->
<aop:aspectj-autoproxy />
</beans>
添加一个切面类
package com.bing.aspect;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @Author IBing
* @Date 2022/8/26 22:01
* @Version 1.0
*/
@Aspect //表示这是一个 切面类
@Component //将对象放入spring容器
public class UserAspect {
//开启日志
private Logger logger = Logger.getLogger(UserAspect.class);
/**
* 目标方法执行之前执行
* @param joinPoint
*/
@Before("execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))")
public void before(JoinPoint joinPoint){
logger.debug("before");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 无论是否抛出异常都会执行,相当于finally
* @param joinPoint
*/
@After("execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))")
public void after(JoinPoint joinPoint){
logger.debug("after");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 相当于try
* @param joinPoint
*/
@AfterReturning("execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))")
public void afterReturning(JoinPoint joinPoint){
logger.debug("afterReturning");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 相当于catch
* @param joinPoint
* @param e
*/
@AfterThrowing(value="execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))",throwing ="e" )
public void afterThrowing(JoinPoint joinPoint,RuntimeException e){
logger.debug("afterThrowing");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("抛出的异常为",e);
}
/**
* 环绕执行
* @param pjd
* @return
* @throws Throwable
*/
@Around("execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))")
public Object around(ProceedingJoinPoint pjd) throws Throwable {
logger.debug("around之前");
Object proceed= pjd.proceed();
logger.debug("around之后");
return proceed;
}
}
测试
@Test
public void test( ){
//创建spring的容器并初始化
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
String[] beanNameForType = classPathXmlApplicationContext.getBeanNamesForType(UserController.class);
System.out.println(Arrays.toString(beanNameForType));
UserController bean = (UserController) classPathXmlApplicationContext.getBean("userController");
bean.login("aa","123"); //这是 UserController 里写好的login方法
classPathXmlApplicationContext.close();
}
输出结果

因为没有异常,所以 **afterThrowing **方法没有执行
上面每个方法的切入点都一样,代码重复,我们可以定义切入点,
//定义切入点
@Pointcut("execution(public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))")
private void pointCut(){}
然后在切面类的方法上使用切入点方法就行,这样就减少了代码重复
/**
* 目标方法执行之前执行
* @param joinPoint
*/
@Before("pointCut()")
public void before(JoinPoint joinPoint){
logger.debug("before");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
execution() 切入点
直接精准到一个方法上面去
execution( public com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))
任意权限修饰符
execution( com.bing.entity.User com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))
无返回类型
execution( void com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))
有返回类型
execution( !void com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))
任意返回类型
execution( * com.bing.service.impl.UserServiceImpl.login(java.lang.String,java.lang.String))
任意参数
execution( * com.bing.service.impl.UserServiceImpl.login(..))
类中的任意方法
execution( * com.bing.service.impl.UserServiceImpl.*(..))
类中以指定内容开头的方法
execution( * com.bing.service.impl.UserServiceImpl.select*(..))
包中的任意类的任意方法不包含子包下面的类
execution( * com.bing.service.impl.*.*(..))
包中及其下的任意类的任意方法
execution( * com.bing.service..*.*(..))
pointcut 切入点 定义切入的连接点, 一般对应的就是表达式
aspect 切面 拥有具体功能的一个类
advice 通知 切面的具体实现 对应的就是切面类中的方法
joinpoint 连接点 程序运行中可以插入切面的地方 在spring中只能是方法 比如login方法
target 目标对象 切入的对象 这个对象包含了业务代码的具体实现 比如:UserServiceImpl类的对象
proxy 代理对象 目标对象应用了通知以后创建的一个新的对象,这个对象中包含了原本的业务实现和扩展实现
weaving 织入 将通知应用到目标对象后创建代理对象的过程
首先在配置文件中进行AOP相应的配置
<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: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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解支持,,让项目支持spring的注解-->
<!-- <context:annotation-config></context:annotation-config>-->
<!--注解扫描 默认开启注解支持-->
<context:component-scan base-package="com.bing">
<!--设置需要扫描的注解-->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>-->
<!--设置不扫描的注解-->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>-->
</context:component-scan>
<!--
打开动态代理
proxy-target-class="true" 就是cglib代理 ,为false则会使用jdk代理实现,默认为false
-->
<aop:aspectj-autoproxy proxy-target-class="false"/>
<!-- 下面这些就是AOP的XML实现方式-->
<bean id="userAspect" class="com.bing.aspect.UserAspect"/>
<aop:config>
<aop:aspect ref="userAspect">
<!-- 定义切面-->
<aop:pointcut id="pc" expression="execution(* com.bing.service.impl.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="pc"/>
<aop:after-returning method="afterReturning" pointcut-ref="pc"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pc" throwing="e"/>
<aop:after method="after" pointcut-ref="pc"/>
<!-- 如果不想使用已经定义的切入点 pc,也可以使用pointcut="execution()"来自己定义,这里演示就使用相同的切入点-->
<aop:around method="around" pointcut="execution(* com.bing.service.impl.UserServiceImpl.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
切面类
package com.bing.aspect;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @Author IBing
* @Date 2022/8/26 22:01
* @Version 1.0
*/
//@Aspect //表示这是一个 切面类
@Component //将对象放入spring容器
public class UserAspect {
private Logger logger = Logger.getLogger(UserAspect.class);
/**
* 目标方法执行之前执行
* @param joinPoint
*/
public void before(JoinPoint joinPoint){
logger.debug("before");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 无论是否抛出异常都会执行,相当于finally
* @param joinPoint
*/
public void after(JoinPoint joinPoint){
logger.debug("after");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 相当于try
* @param joinPoint
*/
public void afterReturning(JoinPoint joinPoint){
logger.debug("afterReturning");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("拦截的方法"+joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
logger.debug("拦截的参数"+joinPoint.getArgs());
logger.debug("拦截的位置"+joinPoint.getStaticPart());
logger.debug("拦截的代理对象"+joinPoint.getStaticPart());
}
/**
* 相当于catch
* @param joinPoint
* @param e
*/
public void afterThrowing(JoinPoint joinPoint,RuntimeException e){
logger.debug("afterThrowing");
logger.debug("拦截的目标对象"+joinPoint.getTarget());
logger.debug("抛出的异常为",e);
}
/**
* 环绕执行
* @param pjd
* @return
* @throws Throwable
*/
public Object around(ProceedingJoinPoint pjd) throws Throwable {
logger.debug("around之前");
Object proceed= pjd.proceed();
logger.debug("around之后");
return proceed;
}
}
运行结果

对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url
几个月前,我读了一篇关于rubygem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。
是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在