Spring的aop详解


Spring的aop详解


applicationContext.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"
       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">


    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
</beans>

自定义的切面
首先定义一个bean

<bean id="diy" class="com.lishao.diy.DiyPointCut"/>

diy的代码为
在这里插入图片描述
切入点代码

<aop:config>
        <!--&lt;!&ndash;自定义切面,ref为引用的类&ndash;&gt;-->
        <aop:aspect ref="diy">
            <!--&lt;!&ndash;切入点&ndash;-->
            <aop:pointcut id="point" expression="execution(* com.lishao.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>


    </aop:config>

在这里插入图片描述
before 切入之前运行
after 切入之后运行
point为 切入的点

以上为自定义切入

注解切入

 <!--注册bean-->
    <bean id="annotationPointCut" class="com.lishao.diy.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>

注册bean,开启注解支持

//方式三:
@Aspect   //标记这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.lishao.service.UserServiceImpl.*(..))")//before里面写的是切入面
    public void before(){
        System.out.println("=======方法执行之前==========");
    }
    @After("execution(* com.lishao.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=======方法执行之后==========");
    }
    @Around("execution(* com.lishao.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");
        //获得签名
        Signature signature = jp.getSignature();
        System.out.println("签名为"+signature);
        Object proceed = jp.proceed();

        System.out.println("环绕后");

        System.out.println(proceed);
    }

}

在before after 环绕around 都得写execution(执行的切入点)
在这里插入图片描述
User Service的代码
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值