Spring(三)
1,AOP 的相关概念
1.1AOP 概述
AOP:全称是 Aspect Oriented Programming 即:面向切面编程。
在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
就是把程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的 基础上,对已有方法进行增强。
作用: 在程序运行期间,不修改源码对已有方法进行增强。
优势: 减少重复代码
提高开发效率
维护方便
实现方式: 使用动态代理技术
2,Spring 中的 AOP
2.1 Spring中基于XML的AOP配置步骤
1,把通知bean也交给spring来管理
2,使用aop:config标签表明开始aop的配置
3,使用aop:aspect标签表明配置切面
id属性: 给切面提供一个唯一标识
ref属性:是指定通知类bean的Id
4,在aop:aspect 标签的内部使用对应标签来配置通知的类型,
就是指定对哪些类的哪些方法进行增强。
现在示例是让printlog方法在切入点方法执行之前执行:
所以是前置通知
aop:before 表示前置通知
method属性:用于指定Logger类中哪个方法是前置通知
pointcut属性:
用于指定切入点表达式,该表达式的含义是指 对业务层
中的哪些方法进行增强
切入点表达式的写法:
关键字: execution( 表达式 )
表达式: 访问修饰符 返回值类型 包名.包名.包名…类名.方法名(参数列表)
public void x.xss.service.AccountServiceImpl.saveAccount()
访问修饰符可以省略
void x.xss.service.AccountServiceImpl.saveAccount()
返回值可以使用通配符表示:表示可以任意返回值
x.xss.service.AccountServiceImpl.saveAccount()
通配符,表示任意包。但是有几级包,就需要写几个*
..*.AccountServiceImpl.saveAccount()
使用…表示当前包及其子类
…AccountServiceImpl.saveAccount()
都可以使用号来实现通配
….*()
可以直接写数据类型:
基本类型直接写名称 int
引用类型写包名.类名的方式 例如 java.lang.string
可以使用通配符表示任意类型,但必须有参数
可以使用…表示有无参数均可,并且有参数则是任意类型
全通配写法:
….*(…)
实际开发中切入点表达式的通常写法:
切到业务层实现类下的所有方法
x.xss.service.impl..(…)
配置文件bean.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">
<!--配置spring的Ioc,并把service对象配置进来-->
<bean id="accountService" class="x.xss.service.AccountServiceImpl"></bean>
<!--配置Logger类 把通知bean交给spring来管理-->
<bean id="logger" class="x.xss.utils.Logger"></bean>
<!--配置aop-->
<aop:config>
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知的类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog"
pointcut="execution(public void x.xss.service.AccountServiceImpl.saveAccount())"></aop:before>
</aop:aspect>
</aop:config>
</beans>
业务层实现类
package x.xss.service;
public class AccountServiceImpl implements AccountService{
public void saveAccount() {
System.out.println("保存了");
}
public void updateAccount(int i) {
System.out.println("修改了");
}
public int deleteAccount() {
System.out.println("删除了");
return 0;
}
}
业务层接口
/**
* 业务层接口
*/
public interface AccountService {
/**
* 模拟保存账户
*/
void saveAccount();
/**
* 模拟修改账户
* @param i
*/
void updateAccount(int i);
/**
* 模拟删除账户
* @return
*/
int deleteAccount();
}
utils包下的记录日志工具类,此类用于在service方法执行之前执行,可用动态代理,但
在spring中可以配置将此类切入
package x.xss.utils;
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
public class Logger {
public void printLog(){
/**
* 用于打印日志,并要求此方法在切入点方法执行之前执行(切入点方法就是业务层方法)
*/
System.out.println("Logger类中的printLog方法开始执行了");
}
}
测试类
/**
* 测试AOP的配置
*/
public class AOPTest {
public static void main(String[] args) {
//1,获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2,获取对象
AccountService as = (AccountService) ac.getBean("accountService");
as.saveAccount();
as.updateAccount(1);
as.deleteAccount();
}
}
通知类型 前置通知,后置通知 ,异常通知, 最终通知
<!-- 配置spring的Ioc,并把service对象配置进来-->
<bean id="accountService" class="x.xss.service.AccountServiceImpl"></bean>
<!-- 配置Logger类-->
<bean id="logger" class="x.xss.utils.Logger"></bean>
<!-- 配置aop-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(public void x.xss.service.AccountServiceImpl.saveAccount())"/>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置前置通知-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
<!--配置后置通知-->
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
<!--配置异常通知-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<!--配置最终通知-->
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
<!--配置切入点表达式
id属性: 用于指定表示的唯一标识
expression 属性: 用于指定表达式内容
此标签写在aop:aspect 切面标签内部,并且只能当前切面使用
当然它也可以写在aop:aspect 外部,此时变成了所有切面可用
放外面,因为受到约束的影响,一定要放在aop:aspect 标签之前
<aop:pointcut id="pt1" expression="execution(public void x.xss.service.AccountServiceImpl.saveAccount())"/> 然后里面的就可以直接使用了!
-->
<!-- 最后还一种方法,环绕通知,同样可以实现 在切入点执行前后的一切通知方法
具体演示 在项目2中-->
</aop:aspect>
</aop:config>
</beans>
package x.xss.utils;
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
public class Logger {
/**
* 前置通知
* 在切入点方法执行之前执行
*/
public void beforePrintLog(){
System.out.println("Logger类中的前置通知方法开始执行");
}
/**
* 后置通知在切入点方法正常执行之后执行,若不是正常执行,而是遇到了异常,则不会执行后置通知
* 而是去执行异常通知,总之 后置通知与异常通知不会同时出现
*
*/
public void afterReturningPrintLog(){
System.out.println("Logger类中的后置通知方法开始执行");
}
/**
* 异常通知
* 在切入点方法执行产生异常后执行
*/
public void afterThrowingPrintLog(){
System.out.println("Logger类中的异常通知方法开始执行");
}
/**
* 最终通知
* 无论切入点方法是否正常执行 都会在最后执行
*/
public void afterPrintLog(){
System.out.println("Logger类中的最终通知方法开始执行");
}
}
环绕通知
**问题:**当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
**分析:**通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
解决:Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
**spring中的环绕通知:**它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
aop:around:
作用: 用于配置环绕通知
属性: method:指定通知中方法的名称。
pointct:定义切入点表达式
pointcut-ref:指定切入点表达式的引用
说明: 它是 spring 框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。
注意: 通常情况下,环绕通知都是独立使用的
<bean id="accountService" class="x.xss.service.AccountServiceImpl"></bean>
<bean id="logger" class="x.xss.utils.Logger"></bean>
<aop:config>
<aop:pointcut id="pt1" expression="execution(public void x.xss.service.AccountServiceImpl.saveAccount())"/>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置环绕通知 详细注释,在Logger类中-->
<aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
</beans>
package x.xss.utils;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
public class Logger {
public Object aroundPringLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
Object[] args = pjp.getArgs();//得到方法执行所需要的参数
System.out.println("Logger类中的aroundPringLog方法开始记录日志..前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPringLog方法开始记录日志。。后置");
return rtValue;
} catch (Throwable t) {
System.out.println("Logger类中的aroundPringLog方法开始记录日志 。。。异常");
throw new RuntimeException(t);
} finally {
System.out.println("Logger类中的aroundPringLog方法开始记录日志。。最终");
}
}
}
2.2,基于注解的 AOP 配置
在配置文件中
<?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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="x.xss"></context:component-scan>
<!-- 配置spring开启注解AOP的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
实现类
@Service("accountService")
public class AccountServiceImpl implements AccountService {
public void saveAccount() {
int a=1/0; //模拟异常
System.out.println("保存了数据");
}
public void updateAccount(int i) {
System.out.println("修改了");
}
public int deleteAccount() {
System.out.println("删除了");
return 0;
}
}
工具类中,也就是切入点 ,在实现类执行之前执行
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* x.xss.service.impl.*.*(..))")
private void pt1(){}
//环绕通知
@Around("pt1()")
public Object aroundPringLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
Object[] args = pjp.getArgs();//得到方法执行所需要的参数
System.out.println("Logger类中的aroundPringLog方法开始记录日志..前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPringLog方法开始记录日志。。后置");
return rtValue;
} catch (Throwable t) {
System.out.println("Logger类中的aroundPringLog方法开始记录日志 。。。异常");
throw new RuntimeException(t);
} finally {
System.out.println("Logger类中的aroundPringLog方法开始记录日志。。最终");
}
}
}
测试类
/**
* 测试AOP的配置
*/
public class AOPTest {
public static void main(String[] args) {
//1,获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2,获取对象
AccountService as = (AccountService) ac.getBean("accountService");
as.saveAccount();
}
}
输出结果:
Logger类中的aroundPringLog方法开始记录日志…前置
Logger类中的aroundPringLog方法开始记录日志 。。。异常
Logger类中的aroundPringLog方法开始记录日志。。最终
正常
在配置中要使用环绕通知,使用前置后置通知可能会乱
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* x.xss.service.impl.*.*(..))")
private void pt1(){}
@Before("pt1()")
public void beforePrintLog(){
System.out.println("Logger类中的前置通知方法开始执行");
}
@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("Logger类中的后置通知方法开始执行");
}
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("Logger类中的异常通知方法开始执行");
}
@After("pt1()")
public void afterPrintLog(){
System.out.println("Logger类中的最终通知方法开始执行");
}
输出结果
Logger类中的前置通知方法开始执行
Logger类中的最终通知方法开始执行
Logger类中的异常通知方法开始执行
最终通知和异常通知错乱了