什么是AOP?
假如有一个功能,很多地方都要用到,怎么办呢?
(1)最原始的方法,就是在每个需要用到的该功能的地方用代码进行实现,很麻烦。
(2)将该功能抽调成一个方法,在每个需要实现该功能的地方调用这个方法。这个办法比上个办法就要简单点了。但是我们仍然需要在每一个需要调用该方法的地方进行插入,还是不方便。
(3)将该功能抽调出来,形成一个单独的模块,并且设置该模块需要插入的位置。这样我们就不需要在每一个地方都调用模块,代码维护比较方便。这种思想就叫做面向切面变成,即AOP。
再说的通俗一点,就拿QQ的自动登录来说,电脑开机第一次打开QQ都需要输入账号密码,然后点击登录,太麻烦了。怎么办呢?设置自动登录,电脑就会记住你的账号密码,在你打开QQ之后,自动帮你登录。输入密码然后点击登录就是要实现的功能,被抽离成一个模块,插入到打开QQ之后。不同的是,AOP可以选择模块插入在某个方法之前,之后,或者在其前后都插入。可能这个比喻不是很恰当,但可以帮助理解AOP是干什么的。
怎么实现AOP?
(1)创建一个Spring项目,导入所需要的jar包
(2)创建业务类 ------ 业务类内的方法相当于主要的功能,我们暂且称为主要功能
package com.entity;
public class Login {
public void login() {
System.out.println("登录");
}
public void logout() {
System.out.println("退出");
}
}
(3)创建切片类 ----切片类内的方法就是在调用主要方法前后需要用到的方法,暂且称为辅助功能
package com.aspect;
public class Aspect {
public void logInConfirm() {
System.out.println("登录前的验证");
}
public void logOutConfirm() {
System.out.println("确定要退出吗");
}
}
(4)配置核心的配置文件
新建other–选择Spring Bean Configuration File命名为applicationContext.xml,直接放在src文件夹下面。
<?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: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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 业务类 -->
<bean id="login" class="com.entity.Login"></bean>
<!-- 切片类 -->
<bean id="aspect" class="com.aspect.Aspect"></bean>
<!-- AOP配置 -->
<aop:config>
<!-- 切点 即需要在前后插入辅助方法的主要方法 -->
<!-- 第一个*表示所有的返回值 注意第一个*后要有空格 -->
<aop:pointcut expression="execution(* com.entity.Login.login(..))" id="pointcut1"/>
<aop:pointcut expression="execution(* com.entity.Login.logout(..))" id="pointcut2"/>
<!-- 切面 -->
<aop:aspect id="aop:aspect" ref="aspect">
<!--before表示在主要方法前插入-->
<!--method是要插入的辅助方法-->
<!--pointcut就是前面的切点-->
<aop:before method="logInConfirm" pointcut-ref="pointcut1"/>
<aop:before method="logOutConfirm" pointcut-ref="pointcut2"/>
</aop:aspect>
</aop:config>
</beans>
(5)进行测试
public class Demo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Login log = (Login) context.getBean("login");
log.login();
log.logout();
}
}
测试结果:
结果发现在登录前会调用我们插入的输入Aspect类中的logInConfirm方法,在推出之前会调用logOutConfirm方法,成功!