打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring用Aop实现计算器验证(注解方式)
//抽象类:ArithnmeticCalulator
public interface ArithnmeticCalulator {
int add(int i,int j);
int sub(int i,int j);
int mul(int i,int j);
int div(int i,int j);
}
//实现抽象类:ArithnmeticCalulator类
@Component("arithnmeticCalulator")
public class ArithnmeticCalulatorImpl implements ArithnmeticCalulator {
实现方法省去.....
}
LogginAspect实现
//把这个类声明为一个切面,需要吧该类放入IOC容器中,在声明一个切面
@Aspect
@Component
public class LogginAspect {
// 定义一个方法,用于声明切入点的表达式,一般在放中不需要添加其他的代码
@Pointcut("execution(* com.wzq.spring.aop.impl.*.*(..))")
public void declareJoinPointExpression() {

}

@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint) {
//获取ArithnmeticCalulator的method方法
String methodName = joinPoint.getSignature().getName();
//获取ArithnmeticCalulator的method值
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + "begins" + args);
}

// 后置通知:在目标方法执行后执行的通知,执行的通通知 //后置通知不会返回结果
@After("declareJoinPointExpression()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + "ends");
// 异常通知
@AfterThrowing(value ="declareJoinPointExpression()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + "execution" + ex);
}
}
XML配置
<!-- 配置bean -->
<bean class="com.wzq.spring.aop.xml.ArithnmeticCalulatorImpl" id="arithnmeticCalulator"></bean>
<!-- 配置切面的bean -->
<bean id="logginAspect" class="com.wzq.spring.aop.xml.LogginAspect"></bean>
main方法
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
ArithnmeticCalulator arithnmeticCalulator = ctx
.getBean(ArithnmeticCalulator.class);
int result = arithnmeticCalulator.sub(6, 6);
System.out.println("result:" + result);
int result1=arithnmeticCalulator.div(10, 0);
System.out.println(result1);
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用Spring AOP 的@AspectJ记录日志
Spring MVC AOP通过注解方式拦截Controller等实现日志管理
java – 投入AOP之后
Spring AOP 简单入门示例
Aspectwerkz动态实现AOP
浅析Spring 2.X中AOP的使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服