Spring切面优先级与基于xml的AOP实现方法详解
一、切面的优先级
①创建类ValidateAspect:
由于要把我们的切面类和我们的目标类来进行ioc容器的一个组件,所以我们需要加上@Component注解,然后由于我们要把当前切面类来标识为一个组件,我们需要@Aspect注解
切面的优先级:
可以通过@Order注解的value属性设置优先级,默认值为Integer的最大值
@Order注解的value属性值越小,优先级越高
@Component
@Aspect
@Order(1)
public class ValidateAspect {
// @Before("execution(* com.tian.spring.aop.annotation.CalculatorImpl.*(..))")
@Before("com.tian.spring.aop.annotation.LoggerAspect.pointCut()")
public void beforeMethod() {
System.out.println("ValidateAspect-->前置通知");
}
}②测试类:
public class AOPTest {
@Test
public void testAOPByAnnotation() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("aop-annotation.xml");
Calculator calculator = ioc.getBean(Calculator.class);
calculator.div(10,1);
}
}二、基于xml的AOP实现(了解)
①复制基于注解的AOP实现的四个接口和类
②删除@Aspect注解(将组件标识为切面),切入点表达式的注解@Pointcut,把方法标识为通知方法的注解@Before...,@Order注解
③创建xml文件
<!--扫描组件-->
<context:component-scan base-package="com.tian.spring.aop.xml"></context:component-scan>
<aop:config>
<!--设置一个公共的切入点表达式-->
<aop:pointcut id="pointCut" expression="execution(* com.tian.spring.aop.xml.CalculatorImpl.*(..))"/>
<!--将IOC容器中的某个bean设置为切面-->
<aop:aspect ref="loggerAspect">
<aop:before method="beforeAdviceMethod" pointcut-ref="pointCut"></aop:before>
<aop:after method="afterAdviceMethod" pointcut-ref="pointCut"></aop:after>
<aop:after-returning method="afterReturningAdviceMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
<aop:after-throwing method="afterThrowingAdvice" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
<aop:around method="aroundAdviceMethode" pointcut-ref="pointCut"></aop:around>
</aop:aspect>
<aop:aspect ref="validateAspect" order="1">
<aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
</aop:aspect>
</aop:config>④测试类:
public class AOPByXMLTest {
@Test
public void testAOPByXML() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("aop-xml.xml");
Calculator calculator = ioc.getBean(Calculator.class);
calculator.add(1,2);
}
}到此这篇关于Spring切面优先级与基于xml的AOP实现方法详解的文章就介绍到这了,更多相关Spring切面优先级内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
IntelliJ IDEA配置Tomcat(完整版图文教程)
这篇文章主要介绍了IntelliJ IDEA配置Tomcat(完整版图文教程),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-05-05
springboot集成druid,多数据源可视化,p6spy问题
这篇文章主要介绍了springboot集成druid,多数据源可视化,p6spy问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-01-01
利用Spring Social轻松搞定微信授权登录的方法示例
这篇文章主要介绍了利用Spring Social轻松搞定微信授权登录的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-12-12


最新评论