怎么理解面向切面编程
面向切面编程就是将我们的业务流程中交叉业务代码,如日志,安全,事务等模块(交叉业务)单独的提取出来形成一份横向的切面,把业务逻辑看成纵向的话,以横向交叉的方式应用到业务流程当中的过程就叫做AOP
面试
Spring的AOP使用的动态代理是:JDK动态代理+CGLIB动态代理技术。Spring在这两种动态代理中灵活切换,如果是代理接口,会默认使用JDK动态代理,如果要代理某个类,这个类没有实现接口,就会切换使用CGLIB。当然,你也可以强制通过一些配置让Spring只使用CGLIB
AOP基于注解实现步骤
-
pom.xml文件配置环境
<repositories> <!--spring里程碑版本的仓库--> <repository> <id>repository.spring.milestone</id> <name>Spring Milestone Repository</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <dependencies> <!--spring context依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.0.0-M2</version> </dependency> <!--spring aspects依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>6.0.0-M2</version> </dependency> <!--junit代理--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
-
编写目标方法
@Service("userService") public class UserService { public void login(){ // 目标方法 System.out.println("系统正在进行身份认证。。。"); } }
-
编写切面类
@Component("logAspect") @Aspect public class LogAspect { // 切面 // 切面 = 通知 + 切点 // 通知就是增强,就是具体的要编写的增强代码 // 这里通知Advice以方法的形式出现。 // “execution(修饰符 返回值类型 全限定类名 方法名(形式参数列表) 异常)” @Before("execution(* com.zp.spring.UserService.*(..))") public void advice(){ System.out.println("增强器!!"); } }
-
编写测试方法
@Test public void testAop(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); UserService userService = applicationContext.getBean("userService", UserService.class); userService.login(); } }
-
配置spring.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: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"> <!--组件扫描--> <context:component-scan base-package="com.zp.spring"/> <!--开启aspectj的自动代理--> <!--spring容器在扫描类的时候,查看该类上是否有@Aspect注解,如果有,则给这个类生成代理对象--> <aop:aspectj-autoproxy/> </beans>