使用简单的方式. AspectJ 方式实现

1.新建一个类,不用实现

1.1类中的方法名随便定义

	public class MyAdivce {
	public void mybefore(String name,int age) {
		System.out.println("前置1"+name+",,,"+age);
	}
	public void mybefore1(String name) {
		System.out.println("前置2"+name);
	}
	public void myaftering() {
		System.out.println("后置2");
	}
	public void myagter() {
		System.out.println("后置1");
	}
	public void mythrow() {
		System.out.println("异常");
	}
	public Object myarround(ProceedingJoinPoint p) throws Throwable{
		System.out.println("执行环绕");
		System.out.println("环绕-前置");
		Object result = p.proceed();
		System.out.println("环绕后置");
		return result;
		
	}
}

1.2建一个类,

public class Demo {
	public void demo01(String name,int age) throws Exception {
			//int i=5/0;
		System.out.println("demo01"+name+"    ,"+age);
	}
	public void demo01(String name) throws Exception {
		//int i=5/0;
	System.out.println("demo01y一个参数"+name);
}
}

1.3配置spring中的applicationContext.xml文件

  <bean id="demo" class="com.oyzk.test.Demo"></bean>
	<bean id="myAdivce" class="com.oyzk.advice.MyAdivce"></bean>
<aop:config>
	<aop:aspect ref="myAdivce">
	<aop:pointcut expression="execution(* com.oyzk.test.Demo.demo01(..)) and args(name,age)" id="mypoint"/>
		<aop:pointcut expression="execution(* com.oyzk.test.Demo.demo01(..)) and args(name)" id="mypoint01"/>
		<aop:pointcut expression="execution(* com.oyzk.test.Demo.demo01(..))" id="mypoint02"/>
	<aop:before method="mybefore1" pointcut-ref="mypoint01" arg-names="name"/>	
	<aop:before method="mybefore" pointcut-ref="mypoint" arg-names="name,age"/>
	<aop:after method="myagter" pointcut-ref="mypoint02"/>
	<aop:after-returning method="myaftering" pointcut-ref="mypoint02"/>
	</aop:aspect>
</aop:config>

注意:
1.2.1 aop:after/ 后置通知,是否出现异常都执行
1.2.2aop:after-returning/后置通知,只有当切点正确是执行
1.2.3aop:after/、aop:after-returning/和aop:after-throwing/的执行顺序和配置顺序有关
1.2.4execution()括号不能扩上args
1.2.5中的and不能使用&&由spring把and解析成&&
1.2.6args名称自定义的,顺序和demo1(参数,参数)对应
1.2.7aop:before/ arg-names=” 名 称 ” 名 称 来 源 于 expression=”” 中 args(),名称必须一样,不然会报错
1.2.7.1 args有几个参数arg-names也必须有几个参数
1.2.7.2arg-names=“”里面的名称 必须和通知方法参数名对应
4:测试类:

public class Test {
	public static void main(String[] args) {
	ApplicationContext ac=new  ClassPathXmlApplicationContext("applicationContext.xml");
	Demo de=ac.getBean("demo",Demo.class);
	try {
		de.demo01("张三",12);
		de.demo01("李四");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		//e.printStackTrace();	
	}
}
}

5:运行结果
在这里插入图片描述作用:不改动源代码,扩张其他功能。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值