spring学习-IoC和DI
spring学习-注解的使用
AOP
AOP为Aspect Oriented Programming的缩写,也就是我们所说的面向切面编程,AOP通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术,AOP是OOP的延续
我个人认为AOP就是可以在不改变方法源码的基础上通过动态代理的方式对方法进行增强,也就是说,它可以在运行到你希望改变的方法时,把增强的方法切进去,而你原本的方法不需要知道切进来的是什么,它只专注自己的工作,减少了代码间的耦合,这就是为啥叫面向切面编程,每一个方法都可以是切点,然后把我们想做的事切到方法去。
举个栗子
我们在进行数据库操作的时候,会加入事务,来确保一致性,防止出现脏数据之类
//保存账户
public void save(Account account) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
accountDao.save(account);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//4.回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
} finally {
//5.释放事务
transactionManager.release();
}
}
//更新账户
public void update(Account account){
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
accountDao.update(account);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//4.回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
} finally {
//5.释放事务
transactionManager.release();
}
}
可以看到每一个方法都有事务操作很繁琐,而方法本身的工作就只有一行代码,则就造成效率很低,我们希望方法只专注于它自己的工作,
所以我们可以把事务的操作抽取出来,通过动态代理的方式,当方法执行的时候,再把事务操作切入进去,这就是AOP思想
Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
//接口的所有方法都会经过这里
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object value = null;
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
value = method.invoke(accountService, args);
//3.提交事务
transactionManager.commit();
//4.返回结果
return value;
} catch (Exception e) {
//4.回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
} finally {
//5.释放事务
transactionManager.release();
}
}
});
@Override
public void save(Account account) {
accountDao.save(account);
}
@Override
public void update(Account account){
accountDao.update(account);
}
可以看到代码减少了很多,方法只需专注于自己的工作
spring中AOP的术语
Joinpoint(连接点): 所有可能的需要注入切面的地方。如方法前后、类初始化、属性初始化前后等等,在spring中,连接点指的就是方法,spring只支持方法类型的连接点
pointCut(切入点): 需要做增强的连接点的称为切入点,切入点都是连接点,但连接点不一定是切入点
Advice(通知): 增强所做的事就是通知,例如前面的事务的操作就是通知,通知又有有前置通知,后置通知,异常通常,最终通知和环绕通知
Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程
Aspect(切面): 通知和切入点的结合
spring基于XML的AOP
在XML中配置AOP时需要加入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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
配置步骤:
1.把通知Bean也交给spring管理
2.使用aop:config标签表明开始AOP的配置
3.使用aop:aspect标签表明配置切面
- id属性:是给切面提供一个唯一的标识
- ref属性:是指定通知类bean的id
4.在aop:aspect标签的内部使用对应标签来配置通知的类型
- aop:before 表示前置通知,aop:after-returning:表示后置通知,aop:after-throwing:异常通知,aop:after:最终通知
- method属性:用于指定配置类中那个方法是前置通知
- pointcut属性:用于指定切入点表达式,该表达式指的是对业务层中那些方法增强
<aop:config>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--前置通知:在切入点方法执行之前执行-->
<aop:before method="beforePrintLog" pointcut="execution(* com.lb.service.impl.*.*(..))"></aop:before>
<!--后置通知:在切入点方法正常执行之后执行-->
<aop:after-returning method="afterPrintLog" pointcut="execution(* com.lb.service.impl.*.*(..))"></aop:after-returning>
<!--异常通知:在切入点方法发生异常后执行-->
<aop:after-throwing method="throwingPrintLog" pointcut="execution(* com.lb.service.impl.*.*(..))"></aop:after-throwing>
<!--最终通知:无论切入点方法是否正常执行都会执行-->
<aop:after method="finalPrintLog" pointcut="execution(* com.lb.service.impl.*.*(..))"></aop:after>
</aop:aspect>
</aop:config>
切入点表达式: 表达对业务层中那些方法增强
关键字:execution(表达式)
表达式:访问修饰符 返回值 全限定类名.方法名(参数列表)
标准写法:public void com.lb.service.impl.AccountSeriveImpl.saveAccount()
访问修饰符可以省略:void com.lb.service.impl.AccountSeriveImpl.saveAccount()
返回值可以使用通配符,表示任意返回值:* com.lb.service.impl.AccountSeriveImpl.saveAccount()
包名也可以用通配符,表示任意包,但是有几级包,就需要写几个*.:* *.*.*.*.AccountSeriveImpl.saveAccount()
包名可以使用..表示当前子包及其子包:* *..AccountSeriveImpl.saveAccount()
类名和方法名都可以使用*来实现通配:* *..*.*()
参数列表:
可以直接写数据类型,基本类型直接写名称,引用类型写包名.类名
可以使用通配符表示任意类型,但必须有参数
可以使用..表示有无参数均可,有参数可以是任意类型
全通配写法:
* *..*.*(..)
通常写法:
切到业务层实现类下的所以方法
* com.lb.service.impl.*.*(..)
为了方便理解,附上一张项目结构图和方法
切入表达式通用化
配置切入点表达式,id:用于指定表达式的唯一id,expression属性用于指定表达式内容,使用pointcut-ref来指定id
此标签放在aop:aspect内部只能当前切面使用,还可放在aop:aspect标签外部,所有切面可用,但必须放在最前面,否则会报错
<aop:pointcut id="pCut" expression="execution(* com.lb.service.impl.*.*(..))"/>
<aop:config>
<aop:pointcut id="pCut" expression="execution(* com.lb.service.impl.*.*(..))"/>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--前置通知:在切入点方法执行之前执行-->
<aop:before method="beforePrintLog" pointcut-ref="pCut" ></aop:before>
<!--后置通知:在切入点方法正常执行之后执行-->
<aop:after-returning method="afterPrintLog" pointcut-ref="pCut"></aop:after-returning>
<!--异常通知:在切入点方法发生异常后执行-->
<aop:after-throwing method="throwingPrintLog" pointcut-ref="pCut"></aop:after-throwing>
<!--最终通知:无论切入点方法是否正常执行都会执行-->
<aop:after method="finalPrintLog" pointcut-ref="pCut"></aop:after>
</aop:aspect>
</aop:config>
spring基于注解的AOP
如果使用XML,则除了需要AOP的约束还需要加上Context的约束
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.lb"/>
<!--配置spring开启注解aop的支持-->
<aop:aspectj-autoproxy/>
</beans>
注解的AOP感觉没啥好讲,注解一看就能知道是什么意思,我注释都简单的介绍了下,有个注意的是使用注解的AOP,最好使用环绕通知,因为注解的通知在调用上有问题
package com.lb.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
/**
* @author LB
* @create 2019-06-17 13:39
* 用于记录日志的工具类,它里面提供了公共的代码
* @EnableAspectJAutoProxy 开启aop注解支持,就不需要xml配置文件了
*/
@Component("logger")
@Aspect//表示当前类是切面类
public class Logger {
//切入点表达式
@Pointcut("execution(* com.lb.service.impl.*.*(..))")
public void pCut(){}
/**
* 前置通知
*/
@Before("pCut()")
public void beforePrintLog(){
System.out.println("前置通知Log....");
}
/**
* 后置通知
*/
@AfterReturning("pCut()")//括号不能忘
public void afterPrintLog(){
System.out.println("后置通知Log....");
}
/**
* 异常通知
*/
@AfterThrowing("pCut()")
public void throwingPrintLog(){
System.out.println("异常通知Log....");
}
/**
* 最终通知
*/
@After("pCut()")
public void finalPrintLog(){
System.out.println("最终通知Log....");
}
/**
* 环绕通知
* spring框架为我们提供了一个接口,ProceedingJoinPoint,该接口有一个proceed方法,此方法就相当于明确调用切入点方法,该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
*/
@Around("pCut()")
public Object aroundPrintLog(ProceedingJoinPoint joinPoint){
Object value = null;
try {
Object[] args = joinPoint.getArgs();
System.out.println("前置通知Log...");
value = joinPoint.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置通知Log...");
return value;
}catch (Throwable t){
System.out.println("异常通知Log...");
throw new RuntimeException(t);
}finally {
System.out.println("最终通知Log...");
}
}
}
之前的文章说过可以通过编写一个配置类来完全摆脱XML,AOP也可以
/**
* @author LB
* @create 2019-06-17 22:59
* @EnableAspectJAutoProxy 开启aop注解支持
*/
@Configuration
@ComponentScan("com.lb")
@EnableAspectJAutoProxy
public class SpringConfig {
}
此次完整测试代码在我的GitHub