AOP配置xml方法学习笔记
介绍下AOP
Spring 框架的一个关键组件是面向方面的编程(AOP)框架。面向方面的编程需要把程序逻辑分解成不同的部分称为所谓的关注点。跨一个应用程序的多个点的功能被称为横切关注点,这些横切关注点在概念上独立于应用程序的业务逻辑。有各种各样的常见的很好的方面的例子,如日志记录、审计、声明式事务、安全性和缓存等。
在 OOP 中,关键单元模块度是类,而在 AOP 中单元模块度是方面。依赖注入帮助你对应用程序对象相互解耦和 AOP 可以帮助你从它们所影响的对象中对横切关注点解耦。
Spring AOP 模块提供拦截器来拦截一个应用程序,例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。
Spring 方面可以使用下面提到的五种通知工作:
| 通知 | 描述 | 
|---|---|
| 前置通知 | 在一个方法执行之前,执行通知。 | 
| 后置通知 | 在一个方法执行之后,不考虑其结果,执行通知。 | 
| 返回后通知 | 在一个方法执行之后,只有在方法成功完成时,才能执行通知。 | 
| 抛出异常后通知 | 在一个方法执行之后,只有在方法退出抛出异常时,才能执行通知。 | 
| 环绕通知 | 在建议方法调用之前和之后,执行通知。 | 
\
建几个类 ,model为实体类,service 为方法和实现类,config为配置类,这里配置了切面 aopBean.xml为xml的配置项

1.引入依赖SpringBoot
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
Spring 的依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
2.构建类

3.方法接口和实现


4.xml中的写法和注释
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bean="http://www.springframework.org/schema/context"
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/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">
<!--如果有下面的注释会导致俩次扫描配置类,导致输出俩次增强信息-->
<!-- <bean:component-scan base-package="com.huawei.swagger.omg"/>-->
<bean id="userService" class="com.huawei.swagger.omg.service.impl.UserServiceImpl"/>
<bean id="aopLogs" class="com.huawei.swagger.omg.config.MyAopLogs"/>
<aop:config>
<!-- 切面,引入log类的位置-->
<aop:aspect id="logs" ref="aopLogs">
<!-- 切点,将切面引入到的位置-->
<!-- execution简写方式,切点可以放在切面上,作用域放大,注意方法的*哪里需要加点-->
<aop:pointcut id="pt" expression="execution(* com.huawei.swagger.omg.service.impl.*.*(..))"/>
<aop:before method="beforeAdvice" pointcut-ref="pt"/>
<aop:after method="afterAdvice" pointcut-ref="pt"/>
<aop:after-returning method="afterNormalAdvice" pointcut-ref="pt" returning="name"/>
<aop:after-throwing method="afterThrowingAdvice" pointcut-ref="pt" throwing="e"/>
<!-- <aop:around method="aroundAdvice" pointcut-ref="pt" arg-names="proceedingJoinPoint"/>-->
</aop:aspect>
</aop:config>
</beans>
如果有一场输出结果

无异常输出结果

springboot报错Could not open ServletContext resource
在xml文件前加classpath试试,或者尝试下修改正确的路径
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号