IoC(控制反转)与AOP(面向切面)是Spring框架的两大核心。Java Spring 框架通过声明式方式灵活地进行事务的管理,提高开发效率和质量。
Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想。
IoC 是指在程序开发中,实例的创建不再由调用者管理,而是由 Spring 容器创建。Spring 容器会负责控制程序之间的关系,而不是由程序代码直接控制,因此,控制权由程序代码转移到了 Spring 容器中,控制权发生了反转,这就是 Spring 的 IoC 思想。
下面我们将结合例子为大家介绍SpringIOC。
1、创建一个maven项目
2、pom.xml文件添加依赖和插件
<!--依赖--> <dependencies> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--spring依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.13.RELEASE</version> </dependency> </dependencies> <!--组件--> <build> <plugins> <!--编译插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
3、创建一个实体类
4、创建spring的配置文件application.xml
5、使用Spring容器创建对象
在配置文件中创建对象
<?xml version="1.0" encoding="UTF-8"?> <!-- Spring的配置文件 beans:跟标签 spring中Java的对象称为Java bean spring-beans。xsd是一个约束文件 约束xml文件都能编写那些标签 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 创建对象:声明bean,告知spring容器创建那些对象 一个bean表示一个对象 id="对象名",要求唯一值 class="完全限定名(带包名,类名)",spring的底层是通过反射方式创建对象,所以不能写接口 相当于com.wlh.bin.Team team1 = new com.wlh.bin.Team();然后将创建的对象放入spring容器的一个集合Map中 springMap.put(id,对象)例如springMap。put("team1",new Team()); scope="singleton":单例,默认值,容器启动完毕之后单例对象就被创建了,而且容器当中只有唯一的对象 scope="prototype":多例,多例的对象是什么是使用什么时候创建,每次获取的时候都创建新对象 --> <bean id="user1" name="team1" class="com.wlh.pojo.User" scope="singleton"></bean> </beans>
6、获取spring容器
Spring 提供了两种 IoC 容器,分别为 BeanFactory 和 ApplicationContext。
6.1、BeanFactory
BeanFactory 是基础类型的 IoC 容器,是一个管理 Bean 的工厂,它主要负责初始化各种 Bean,并调用
它们的生命周期方法。
BeanFactory 接口有多个实现类,最常见的是
org.Springframework.beans.factory.xml.XmlBeanFactory,它是根据 XML 配置文件中的定义装配
Bean 的。
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource(Spring配置文件 的名称));
6.2、ApplicationContext
ApplicationContext 是 BeanFactory 的子接口,也被称为应用上下文。它不仅提供了 BeanFactory 的
所有功能,还添加了对 i18n(国际化)、资源访问、事件传播等方面的良好支持。
ApplicationContext 接口有两个常用的实现类:
6.2.1、ClassPathXmlApplicationContext——常用
该类从类路径 ClassPath 中寻找指定的 XML 配置文件,找到并装载完成 ApplicationContext 的实例化
工作
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(Spring配 置文件的名称.xml);
6.2.2、FileSystemXmlApplicationContext
FileSystemXmlApplicationContext与 ClassPathXmlApplicationContext 的区别是:在读取 Spring 的配置文件时,FileSystemXmlApplicationContext 不再从类路径中读取配置文件,而是通过参数指定配置文件的位置,它可以获取类路径之外的资源,如“D:\application.xml”。
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation);
7、通过上下文对象获取容器中的对象
package com.wlh.test; import com.wlh.pojo.User; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.FileSystemResource; /** * @projectName: MySpring * @package: com.wlh.test * @className: Test01 * @author: 王立宏 * @description: TODO * @date: 2022/1/10 21:38 * @version: 1.0 */ public class Test01 { @Test public void test01() { //spring容器创建对象的方式 String springConfig="application.xml"; //获取容器 // 方法1:路径读取会有问题 //BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource(springConfig)); //Object team1 = beanFactory.getBean("team1");//根据id从IOC容器获取对象 // 方法2: //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("C:/具体路径") // 方法3:常用方法 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(springConfig); //从容器中根据ID获取对象 User team1 = (User) applicationContext.getBean("team1"); System.out.println(team1); //关闭容器 applicationContext.close(); } }
8、关闭容器
applicationContext.close();
对于 DI(DI—Dependency Injection,即“依赖注入”) 使用注解,将不再需要在 Spring 配置文件中声明 bean 实例。Spring 中使用注解,需要在原有Spring 运行环境基础上再做一些改变。
1、声明Bean的注解 @Component
在类上添加注解@Component表示该类创建对象的权限交给Spring容器。注解的value属性用于指定
bean的id值,value可以省略。
@Component 不指定 value 属性,bean 的 id 是类名的首字母小写。
package com.wlh.pojo; import org.springframework.stereotype.Component; /** * @projectName: MySpring * @package: com.wlh.pojo * @className: Team * @author: 王立宏 * @description: TODO * @date: 2022/1/10 21:23 * @version: 1.0 */ @Component(value = "user") public class User { private int id; private String name; private int age; public User() { System.out.println("id:"+id+",姓名:"+name+",年龄:"+age); } }
除此之外,Spring中还提供了其他3个用于创建对象的注解:
@Repository : 用于dao实现类的的注解
@Service: 用户service实现类的注解
@Controller: 用于controller实现类的注解
这三个注解与@Component 都可以创建对象,但这三个注解还有其他的含义,@Service创建业务层对象,业务层对象可以加入事务功能,@Controller 注解创建的对象可以作为处理器接收用户的请求。
@Repository,@Service,@Controller 是对@Component 注解的细化,标注不同层的对象。即持久层对象,业务层对象,控制层对象。
2、包扫描
需要在 Spring 配置文件中配置组件扫描器,用于在指定的基本包中扫描注解。如果没有包扫描,添加的创建对象的注解不生效。
如果要扫描的包有多个,可以有以下方式扫描:
2.1、使用多个context:component-scan指定不同的包路径
<?xml version="1.0" encoding="UTF-8"?> <!-- Spring的配置文件 beans:跟标签 spring中Java的对象称为Java bean spring-beans。xsd是一个约束文件 约束xml文件都能编写那些标签 --> <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" 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 "> <!-- context:component-scan 表示告知spring要扫描的包 这些包以及子包中的类如果添加了@Component注解,则这些添加了@Component注解的类就交给了spring容器创建对象 注意:在beans标签中添加如下内容 xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " --> <context:component-scan base-package="com.wlh.bin"></context:component-scan> <context:component-scan base-package="com.wlh.service"></context:component-scan> <context:component-scan base-package="com.wlh.controller"></context:component-scan> </beans>
2.2、指定 base-package的值使用分隔符
分隔符可以使用逗号(,)分号(;)还可以使用空格,不建议使用空格。
<context:component-scan base-package="com.wlh.bin:com.wlh.service:com.wlh.controller"></context:component-scan>
2.3、base-package是指定到父包名
base-package 的值表示基本包,容器启动会扫描包及其子包中的注解,当然也会扫描到子包下级的子包。所以 base-package 可以指定一个父包就可以。
但不建议使用顶级的父包,扫描的路径比较多,导致容器启动时间变慢。指定到目标包和合适的。也就是注解所在包全路径。
<!--多个包的扫描: 方式3: base-package中直接声明要扫描的多个包的父包--> <context:component-scan base-package="com.wlh"></context:component-scan>
3、属性注入@Value
需要在属性上使用注解@Value,该注解的 value 属性用于指定要注入的值。使用该注解完成属性注入时,类中无需 setter。当然,若属性有 setter,则也可将其加到 setter 上。
(1)、byType自动注入@Autowired
需要在引用属性上使用注解@Autowired,该注解默认使用按类型自动装配 Bean 的方式。使用该注解完成属性注入时,类中无需 setter。当然,若属性有 setter,则也可将其加到 setter 上。
(2)、byName自动注入@Autowired和@Qualifier
需要在引用属性上联合使用注解@Autowired 与@Qualifier。@Qualifier 的 value 属性用于指定要匹配的 Bean 的 id 值。类中无需 set 方法,也可加到 set 方法上。
@Autowired 还有一个属性 required,默认值为 true,表示当匹配失败后,会终止程序运行。若将其值设置为 false,则匹配失败,将被忽略,未匹配的属性值为 null。
(3)、自动注入@Resource
Spring提供了对 jdk中@Resource注解的支持。@Resource 注解既可以按名称匹配Bean,也可以按类型匹配 Bean。默认是按名称注入。使用该注解,要求 JDK 必须是 6 及以上版本。@Resource 可在属性上,也可在 set 方法上。
(3.1)、byType注入引用类型属性
@Resource 注解若不带任何参数,采用默认按名称的方式注入,按名称不能注入 bean,则会按照类型进行 Bean 的匹配注入。
(3.2)、byName注入引用类型属性
@Resource 注解指定其 name 属性,则 name 的值即为按照名称进行匹配的 Bean 的 id。
AOP为Aspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP的作用:不修改源码的情况下,程序运行期间对方法进行功能增强。
好处:
1、减少代码的重复,提高开发效率,便于维护。
2、专注核心业务的开发。
核心业务和服务性代码混合在一起
开发中:各自做自己擅长的事情,运行的时候将服务性代码织入到核心业务中。
通过spring工厂自动实现将服务性代码以切面的方式加入到核心业务代码中。
什么是代理模式?
代理:自己不做,找人帮你做。
代理模式:在一个原有功能的基础上添加新的功能。
分类:静态代理和动态代理。
1、原有方式:核心业务和服务方法都编写在一起
package com.wlh.service; public class UserService { public void add(){ try { System.out.println("开始事务"); System.out.println("UserService---- add----");// 核心业务 System.out.println("提交事务"); } catch (Exception e) { e.printStackTrace(); System.out.println("回滚事务"); } } }
2、基于类的静态代理
将服务性代码分离出来,核心业务–保存业务中只有保存功能
package com.wlh.service; public class UserService { public void add(){ System.out.println("UserService---- add----");// 核心业务 } }
package com.wlh.staticproxy; import com.wlh.service.UserService; /** * 基于类的静态代理: * 要求继承被代理的类 * 弊端:每次只能代理一个类 */ public class ProxyUserService extends UserService { public void add(){ try { System.out.println("开始事务"); super.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成 System.out.println("提交事务"); }catch (Exception e){ System.out.println("回滚事务"); } } }
public static void main(String[] args) { UserService us=new ProxyUserService(); us.add(); }
弊端:代理类只能代理一个类
3、基于接口的静态代理
为核心业务(保存add)创建一个接口,通过接口暴露被代理的方法
要求:代理类和被代理类都实现了同一个接口
package com.wlh.service; /** * 接口定义核心方法 */ public interface IService { void add(); }
package com.wlh.service; public class UserService implements IService{ @Override public void add(){ System.out.println("UserService---- add----");// 核心业务 } }
package com.wlh.staticproxy; import com.wlh.service.IService; /** * 基于接口的静态代理: * 代理类和被代理类实现同一个接口 */ public class ProxyTranService implements IService { private IService service;//被代理的对象 public ProxyTranService(IService service) { this.service = service; } @Override public void add() { try { System.out.println("开始事务"); service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成 System.out.println("提交事务"); }catch (Exception e){ System.out.println("回滚事务"); } } }
package com.wlh.staticproxy; import com.wlh.service.IService; public class ProxyLogService implements IService { private IService service;//被代理对象 public ProxyLogService(IService service) { this.service = service; } @Override public void add() { try { System.out.println("开始日志"); service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成 System.out.println("结束日志"); }catch (Exception e){ System.out.println("异常日志"); } } }
测试类
public static void main(String[] args) { UserService userService=new UserService();//被代理对象 ProxyTranService tranService=new ProxyTranService(userService);//事务代理对象--一级代理 //tranService.add();//代理对象干活 ProxyLogService logService=new ProxyLogService(tranService);//日志的代理对象--二级代理 logService.add(); }
4、提取出切面代码,作为AOP接口
共有4个位置可以将切面代码编织进入核心业务代码中。
package com.wlh.aop; /** * 切面:服务代码,切入到核心代码中,切入到哪里,给了四个位置 */ public interface AOP { void before(); void after(); void exception(); void myFinally(); }
package com.wlh.aop; public class TranAOP implements AOP { @Override public void before() { System.out.println("事务----before"); } @Override public void after() { System.out.println("事务----after"); } @Override public void exception() { System.out.println("事务----exception"); } @Override public void myFinally() { System.out.println("事务----myFinally"); } }
package com.wlh.aop; public class LogAop implements AOP{ @Override public void before() { System.out.println("日志----before"); } @Override public void after() { System.out.println("日志----after"); } @Override public void exception() { System.out.println("日志----exception"); } @Override public void myFinally() { System.out.println("日志----myFinally"); } }
package com.wlh.staticproxy; import com.wlh.aop.AOP; import com.wlh.service.IService; public class ProxyAOPService implements IService { private IService service;//被代理对象 private AOP aop;//要加入切面 public ProxyAOPService(IService service, AOP aop) { this.service = service; this.aop = aop; } @Override public void add() { try { aop.before(); service.add();//被代理对象干活 aop.after(); }catch (Exception e){ aop.exception(); }finally { aop.myFinally(); } } }
@Test public void test02(){ IService userService=new UserService();//被代理对象--核心内容 AOP logAop=new LogAop();//切面-服务内容 AOP tranAop=new TranAOP(); IService service=new ProxyAOPService(userService,logAop); //代理对象--一级代理 IService service2=new ProxyAOPService(service,tranAop);//代理对象--二级代理 service2.add(); }
总结静态代理: (1)优点: 可以做到在不修改目标对象的功能前提下,对目标对象功能扩展。 (2)缺点: 因为代理对象,需要与目标对象实现一样的接口。所以会有很多代理类,类太多。 一旦接口增加方法,目标对象与代理对象都要维护。
静态代理:要求代理类一定存在,
动态代理:程序运行的时候,根据要被代理的对象动态生成代理类。
类型:
1、基于JDK的动态代理
2、基于CGLIB的动态代理
1、直接编写测试类
/* newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandlerh) ClassLoader :类加载器,因为动态代理类,借助别人的类加载器。一般使用被代理对象的类加载器。 Class<?>[] interfaces:接口类对象的集合,针对接口的代理,针对哪个接口做代理,一般使用的就是被代理对象的接口。 InvocationHandler:句柄,回调函数,编写代理的规则代码 public Object invoke(Object arg0, Method arg1, Object[] arg2) Object arg0:代理对象 Method arg1:被代理的方法 Object[] arg2:被代理方法被执行的时候的参数的数组 */
package com.wlh.dynamicproxy; import com.wlh.service.IService; import com.wlh.service.UserService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MyJDKProxy { public static void main(String[] args) { //目标对象--被代理对象 UserService userService=new UserService(); //返回代理对象 调用JDK中Proxy类中的静态方法newProxyInstance获取动态代理类的实例 IService proxyService= (IService) Proxy.newProxyInstance( userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {//回调函数 编写代理规则 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { System.out.println("开始事务"); Object invoke = method.invoke(userService, args);//核心业务 System.out.println("提交事务"); return invoke; }catch (Exception e){ System.out.println("回滚事务"); e.printStackTrace(); throw e; }finally { System.out.println("finally---------"); } } } ); //代理对象干活 proxyService.add(); System.out.println(userService.getClass()); System.out.println(proxyService.getClass()+"--------"); } }
2、结构优化
方法1:
package com.wlh.dynamicproxy; import com.wlh.aop.AOP; import com.wlh.service.IService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ProxyHandler implements InvocationHandler { private IService service;//目标对象 private AOP aop;//切面 public ProxyHandler(IService service, AOP aop) { this.service = service; this.aop = aop; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { aop.before(); Object invoke = method.invoke(service, args);//核心业务 aop.after(); return invoke; }catch (Exception e){ aop.exception(); e.printStackTrace(); throw e; }finally { aop.myFinally(); } } }
public static void main2(String[] args) { //目标对象--被代理对象 UserService userService=new UserService (); //切面 AOP tranAop=new TranAOP(); //返回代理对象 基于JDK的动态代理 IService proxyService= (IService) Proxy.newProxyInstance( userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), new ProxyHandler(userService,tranAop) ); //代理对象干活 proxyService.add(); System.out.println(userService.getClass()); System.out.println(proxyService.getClass()+"------"); }
方法2:
package com.wlh.dynamicproxy; import com.wlh.aop.AOP; import com.wlh.service.IService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory { private IService service;//目标对象 private AOP aop;//切面 public ProxyFactory(IService service, AOP aop) { this.service = service; this.aop = aop; } /** * 获取动态代理的示例 * @return */ public Object getProxyInstance() { return Proxy.newProxyInstance( service.getClass().getClassLoader(), service.getClass().getInterfaces(), new InvocationHandler() {//回调函数 编写代理规则 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { aop.before(); Object invoke = method.invoke(service, args);//核心业务 aop.after(); return invoke; }catch (Exception e){ aop.exception(); e.printStackTrace(); throw e; }finally { aop.myFinally(); } } } ); } }
public static void main(String[] args) { //目标对象--被代理对象 UserService userService=new UserService (); //切面 AOP tranAop=new TranAOP(); AOP logAop=new LogAop(); //获取代理对象 IService service= (IService) new ProxyFactory(userService,tranAop).getProxyInstance(); IService service1= (IService) new ProxyFactory(service,logAop).getProxyInstance(); service1.add();//核心业务+服务代码混合在一起的完整的业务方法 }
代理对象不需要实现接口,但是目标对象一定要实现接口;否则不能用JDK动态代理。
如果想要功能扩展,但目标对象没有实现接口,怎样功能扩展?
子类的方式实现代理CGLIB。
Cglib代理,也叫做子类代理。在内存中构建一个子类对象从而实现对目标对象功能的扩展。
1、JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。如果想代理没有实现接口的类,就可以使用CGLIB实现。
2、CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接口。它广泛的被许多AOP的框架使用,例如Spring AOP和dynaop,为他们提供方法的interception。
3、CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。不鼓励直接使用ASM,因为它要求你必须对JVM内部结构包括class文件的格式和指令集都很熟悉。
1、 直接编写测试类
package com.wlh.cglibproxy; public class NBAService { public int add(String name,int id){ System.out.println("NBAService---- add----"); return id; } }
public static void main(String[] args) { //目标对象:没有接口 NBAService nbaService=new NBAService(); //创建代理对象:选择cglib动态代理 NBAService proxyService= (NBAService) Enhancer.create(nbaService.getClass(), new MethodInterceptor() {//回调函数编写代理规则 @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { try { System.out.println("开始事务"); Object invoke = methodProxy.invokeSuper(o, objects);//核心 System.out.println("提交事务"); return invoke; }catch (Exception e){ System.out.println("事务回滚"); throw e; }finally { System.out.println("finally------------"); } } }); //代理对象干活 int res=proxyService.add("huren",1001); System.out.println(res); }
2、结构化设计方式
package com.wlh.cglibproxy; import com.wlh.aop.AOP; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class CglibProxyFactory { //目标对象 private NBAService nbaService;//没有实现接口的 //切面 private AOP aop;//切面 /** * 创建代理对象 * @param nbaService * @param aop * @return */ public Object getProxyInstance(NBAService nbaService,AOP aop){ return Enhancer.create(nbaService.getClass(), new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { try { aop.before(); Object o1 = methodProxy.invokeSuper(o, objects); aop.after(); return o1; }catch (Exception e){ aop.exception(); throw e; } finally { System.out.println("finally-----------"); } } }); } }
public static void main(String[] args) { //目标对象:没有接口 NBAService nbaService=new NBAService(); //创建切面 AOP tranAop=new TranAOP(); //创建代理对象:选择cglib动态代理 NBAService proxyInstance = (NBAService) new CglibProxyFactory().getProxyInstance(nbaService, tranAop); int res=proxyInstance.add("huren",1001); System.out.println(res); }
Spring的AOP实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
我们先来介绍AOP的相关术语:
Target(目标对象):
要被增强的对象,一般是业务逻辑类的对象。
Proxy(代理):
一个类被 AOP 织入增强后,就产生一个结果代理类。
Aspect(切面):
表示增强的功能,就是一些代码完成的某个功能,非业务功能。是切入点和通知的结合。
Joinpoint(连接点):
所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法(一般是类中的业务方法),因为Spring只支持方法类型的连接点。
Pointcut(切入点):
切入点指声明的一个或多个连接点的集合。通过切入点指定一组方法。
被标记为 final 的方法是不能作为连接点与切入点的。因为最终的是不能被修改的,不能被增强的。
Advice(通知/增强):
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。通知定义了增强代码切入到目标代码的时间点,是目标方法执行之前执行,还是之后执行等。通知类型不同,切入时间不同。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
切入点定义切入的位置,通知定义切入的时间。
Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
切面的三个关键因素: 1、切面的功能--切面能干啥 2、切面的执行位置--使用Pointcut表示切面执行的位置 3、切面的执行时间--使用Advice表示时间,在目标方法之前还是之后执行。
对于 AOP 这种编程思想,很多框架都进行了实现。Spring 就是其中之一,可以完成面向切面编程。AspectJ 也实现了 AOP 的功能,且其实现方式更为简捷而且还支持注解式开发。所以,Spring 又将AspectJ 的对于 AOP 的实现也引入到了自己的框架中。
在 Spring 中使用 AOP 开发时,一般使用 AspectJ 的实现方式
AspectJ 是一个优秀面向切面的框架,它扩展了 Java 语言,提供了强大的切面实现。
AspectJ 中常用的通知有5种类型:
AspectJ 定义了专门的表达式用于指定切入点。 表达式的原型如下: execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?) 说明: modifiers-pattern] 访问权限类型 ret-type-pattern 返回值类型 declaring-type-pattern 包名类名 name-pattern(param-pattern) 方法名(参数类型和参数个数) throws-pattern 抛出异常类型 ?表示可选的部分
以上表达式共 4 个部分。
execution(访问权限 方法返回值 方法声明(参数) 异常类型)
切入点表达式要匹配的对象就是目标方法的方法名。所以,execution 表达式中就是方法的签名。
PS:表达式中黑色文字表示可省略部分,各部分间用空格分开。在其中可以使用以下符号:
符号 | 意义 |
---|---|
* | 0-多个任意字符 |
… | 用在方法参数中,表示任意个参数;用在包名后,表示当前及其子包路径 |
+ | 用在类名后,表示当前及其子类;用在接口后,表示当前接口及其实现类 |
示例: execution(* com.kkb.service.*.*(..)) 指定切入点为:定义在 service 包里的任意类的任意方法。 execution(* com.kkb.service..*.*(..)) 指定切入点为:定义在 service 包或者子包里的任意类的任意方法。“..”出现在类名中时,后面必须跟“*”,表示包、子包下的所有类。 execution(* com.kkb.service.IUserService+.*(..)) 指定切入点为:IUserService 若为接口,则为接口中的任意方法及其所有实现类中的任意方法;若为类,则为该类及其子类中的任意方法。
开发阶段:关注核心业务和AOP代码。
运行阶段:spring框架会在运行的时候将核心业务和AOP代码通过动态代理的方式编织在一起。
代理方式的选择:是否实现了接口:有接口就选择JDK动态代理;没有就选择CGLIB动态代理。
1、创建项目引入依赖
<dependencies> <!--spring 核心依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.15</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.15</version> </dependency> <!--测试依赖--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!--编译插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
2、创建spring配置文件引入约束
<?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/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 "> <!--在beans标签中 引入AOP和context约束--> </beans>
3、创建核心业务类
创建的文件目录:
package com.wlh.service; public interface IService { void add(int id, String name); boolean update(int num); }
package com.wlh.service; import org.springframework.stereotype.Service; /** * @projectName: MySpring * @package: com.wlh.service * @className: UserService * @author: 王立宏 * @description: 核心业务类 * @date: 2022/1/24 16:49 * @version: 1.0 */ @Service //将该类加入到容器中 public class UserService implements IService{ @Override public void add(int id, String name) { //int a = 1/0; System.out.println("UserService---------> add"); } @Override public boolean update(int num) { System.out.println("UserService---------> update"); if (num > 666) return true; return false; } }
4、定义切面类
package com.wlh.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @projectName: MySpring * @package: com.wlh.aop * @className: MyAspect * @author: 王立宏 * @description: 切面类 * @date: 2022/1/24 16:56 * @version: 1.0 */ @Component //切面对象的创建权限依然交给sprin给容器 @Aspect //aspectj 框架的注解 标识当前类是一个切面类 public class MyAspect { /** * Pointcut 注解表示 切入点表达式 , 方法一般声明为私有 * 其他的通知可以直接在value属性值直接使用方法名称 ----> 比如before方法可以改为下方注释掉的样子 * 推存使用切入点表达式的方法,方便将来更改表达式 */ @Pointcut("execution(* com.wlh.service..*.*(..))") private void poinCut() { } @Pointcut("execution(* com.wlh.service..*.add*(..))") private void poinCut2() { } /** * 声名为前置通知 execution(* com.wlh.service..*.*(..)) --> 切入点的表达式,表示在那些方法的前面切入 * @param joinPoint */ @Before("execution(* com.wlh.service..*.*(..))") public void before(JoinPoint joinPoint) { System.out.println("前置通知:在目标方法执行之前被调用"); String name = joinPoint.getSignature().getName(); System.out.println("\t\t拦截到的方法的名称:"+name); Object[] args = joinPoint.getArgs(); System.out.println("\t\t方法参数的个数:"+args.length); System.out.println("\t\t方法的参数列表:"); for (Object arg : args) { System.out.println("\t\t\t\t\t"+arg); } } /*@Before("pointCut()") public void before(JoinPoint joinPoint) { System.out.println("前置通知:在目标方法执行之前被调用"); String name = joinPoint.getSignature().getName(); System.out.println("\t\t拦截到的方法的名称:"+name); Object[] args = joinPoint.getArgs(); System.out.println("\t\t方法参数的个数:"+args.length); System.out.println("\t\t方法的参数列表:"); for (Object arg : args) { System.out.println("\t\t\t\t\t"+arg); } }*/ /** * AfterReturning 声明后置通知 * value属性表示切入点表达式 * returning属性表示 返回的结果,如果需要的话可以在后置通知的方法中修改结果 * @param resurt 结果 */ @AfterReturning(value = "execution(* com.wlh.service..*.update*(..))", returning = "resurt") public Object afterReturn(Object resurt) { if (resurt != null) { boolean res = (boolean) resurt; res = (boolean) resurt; if (res) { resurt = false; } } System.out.println("后置通知:在目标方法执行之后被调用,result="+resurt); return resurt; } /** * AfterThrowing 注解声明异常通知方法 * @param ex * @param joinPoint 拦截到的方法 */ @AfterThrowing(value = "execution(* com.wlh.service..*.add*(..))",throwing = "ex") public void exception(JoinPoint joinPoint, Throwable ex) { //一般会把异常发生的时间、位置、原因 都记录下来 System.out.println("异常通知:在目标方法执行出现异常时被调用,否则不会被调用"); Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("\t\t报异常的方法:"+joinPoint.getSignature()+ "\n\t\t异常信息:"+ex.getMessage()+ "\n\t\t异常时间:"+simpleDateFormat.format(date)); } /*@AfterThrowing(value = "pointCut2()",throwing = "ex") public void exception(JoinPoint joinPoint, Throwable ex) { //一般会把异常发生的时间、位置、原因 都记录下来 System.out.println("异常通知:在目标方法执行出现异常时被调用,否则不会被调用"); Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("\t\t报异常的方法:"+joinPoint.getSignature()+ "\n\t\t异常信息:"+ex.getMessage()+ "\n\t\t异常时间:"+simpleDateFormat.format(date)); }*/ /** * After 注解声明为最终通知 注意不要和后置通知混淆 */ @After(value = "execution(* com.wlh.service..*.*(..))") public void myFinally() { System.out.println("最终通知:无论是否出现异常都是最后被调用的通知"); } /** * Around 注解声明环绕通知 * 环绕通知:在目标方法执行之前和之后都执行的方法 * ProceedingJoinPoint 中的 proceed 表示目标方法被执行 * @return */ @Around(value = "execution(* com.wlh.service..*.add*(..))") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("=======环绕方法:在目标方法执行之前"); Object proceed = pjp.proceed(); System.out.println("=======环绕方法:在目标方法执行之后"); return proceed; } }
5、业务类和切面类添加注解
该部分我已经在前面的代码中完成,故在此仅做补充。添加的部分如图:
注意:
配置文件中需要添加如下内容:
<!--包扫描--> <context:component-scan base-package="com.wlh.service ; com.wlh.aop"/> <!--开启注解AOP的使用--> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- aop:aspectj-autoproxy的底层是由 AnnotationAwareAspectJAutoProxyCreator 实现的, 是基于 AspectJ 的注解适配自动代理生成器。 其工作原理是,aop:aspectj-autoproxy通过扫描找到@Aspect 定义的切面类, 再由切面类根据切入点找到目标类的目标方法,再由通知类型找到切入的时间点。 -->
在定义好切面 Aspect 后,需要通知 Spring 容器,让容器生成“目标类+ 切面”的代理对象。这个代理是 由容器自动生成的。只需要在 Spring 配置文件中注册一个基于 aspectj 的自动代理生成器,其就会自动 扫描到@Aspect 注解,并按通知类型与切入点,将其织入,并生成代理。
6、测试类
package com.wlh.test; import com.wlh.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @projectName: MySpring * @package: com.wlh.test * @className: Test01 * @author: 王立宏 * @description: TODO * @date: 2022/1/24 17:06 * @version: 1.0 */ public class Test01 { @Test public void test01() { ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml"); UserService userService = (UserService) ac.getBean("userService"); userService.add(1001,"张大仙"); System.out.println("============================================================"); boolean update = userService.update(8888); System.out.println("update的结果:"+update); } }