基于spring的Around +Pointcut的小案例

配置文件

<?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 https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--    声明目标对象-->
<bean id="s" class="my.myPointcut.SomeserviceImpl"></bean>
    <!--    切面类对象-->
<bean id="ss" class="my.myPointcut.MyaspectJ"></bean>

    <!--    声明自动代理生成器-->
    <aop:aspectj-autoproxy/>
    <aop:config proxy-target-class="true"></aop:config>
    

</beans>

切面类

package my.myPointcut;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyaspectJ {
//@Around(value = "execution(public * my.myPointcut.SomeserviceImpl.do*(..))")
    @Around(value = "abc()")
    public String my(ProceedingJoinPoint pjp) throws Throwable {
    Object[] a=pjp.getArgs();
    String name="";
    int age = 0;
    if (a.length>0&& a!=null){
        name= (String) a[0];
        age= (int) a[1];
    }
        System.out.println("环绕通知运行成功");
        pjp.proceed();
    System.out.println("获得目标方法的第一个参数是;"+name+",第二个是;"+age);
        return "这是环绕通知的返回值";
    }

    @Pointcut(value = "execution(public * my.myPointcut.SomeserviceImpl.do*(..))")
    public void abc(){

    }

}
目标对象
package my.myPointcut;

public class SomeserviceImpl implements Someservice{
    @Override
    public String  dosome(String name, int age) {
        System.out.println("dosome方法实现了");
        return  "dosome方法的返回值";
    }
}
package my.myPointcut;

public interface Someservice {
    String dosome(String name,int age);
}

测试类

package my.myPointcut;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
    public static void main(String[] args) {
        String config="myPointcut.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(config);
        SomeserviceImpl someservice= (SomeserviceImpl) ac.getBean("s");
       String s= someservice.dosome("小明",20);
        System.out.println(s);
    }
}

运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值