栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring AOP编程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring AOP编程

以AOP的方式编程。
已知OrderService类,其中有新增订单的方法saveOrder(),该方法有订单号、订单操作人Id和角色3个参数,该方法用于数据库表order的插入操作。代码如下:

package com.order.service;
public class OrderService{
    public boolean saveOrder(String orderId, String operatorId, String role) {
        System.out.println(operatorId + "完成了订单的新增操作");
        // 完成数据插入的操作………………
        return true;
    }
}

要求以注解的方式实现:
1.编写环绕通知,实现角色验证的功能,即只有role是"admin"的时候才可以调用saveOrder方法。编写Test类测试。
2.编写最终通知,实现记录日志的功能,即不管saveOrder方法是否执行出现异常,都要记录日志(日志的记录功能是:只要在控制台打印当前时间即可)。编写Test类测试。

OrserService.java:

import org.springframework.stereotype.Component;

//业务类
@Component("OrderService")
public class OrserService {

	
	public boolean saveOrder(String orderId, String operatorId, String role) {

		System.out.println(operatorId + "完成了订单的新增操作");

		// 完成数据插入的操作………………

		return true;
	}
}

OrderAdvice.java:

import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class OrderAdvice {

	
	@Around("execution(* com.order.service.*.*(..))")
	public Object verificationRole(ProceedingJoinPoint joinPoint) {

		Object[] param = joinPoint.getArgs();
		String role = (String) param[2];

		Object result = false;
		if (role.equals("admin")) {
			try {
				// 执行调用saveOrder方法
				result = joinPoint.proceed(param);
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	
	@After("execution(* com.order.service.*.*(..))")
	public void writeLog(JoinPoint joinPoint) {
		System.out.println("当前时间:" + new Date().toLocaleString());
	}
	//@Around("execution(* com.order.service.*.*(..))")com.order.service包下所有的类和方法都会进行权限的校验
	//@After("execution(* com.order.service.*.*(..))")com.order.service包下所有的类和方法都会记录日志

}

Test.java:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.order.service.OrserService;

public class Test {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		OrserService orderService = (OrserService) applicationContext.getBean("OrderService");

		boolean result = orderService.saveOrder("1", "1", "admin");

		System.out.println("Test中的main方法:" + result);
	}

}

beans.xml:


	
	
	
	

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915415.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号