业务
业务可分为核心业务和拓展业务.
核心业务:
功能模块的实现业务
拓展业务:
日志,缓存,权限
拓展业务实现方式有两种:
创建标记注解, 自定义注解,用于此注解描述需要指定拓展业务的方法,简而言之就是标记
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface RequiredLog {String value() default "";}
使用
@Pointcut定义切入点表达式,需要在表达式中描述定义切入点的方法
表达式定义方式:采用注解方式的表达式,常用方式如下:
- 注解方式:
@Pointcut("@annotation(com.jt.annotations.RequiredLog)"),参数为需要执行拓展业务的注解的全路径 - Bean方式:
@Pointcut("bean(resourceController)")参数为bean名称 - within方式:
@Pointcut("within(com.jt.controller.ResourceController)")@Slf4j@Component@Aspectpublic class LogAspect {/*** 使用@Pointcut定义切入点表达式,需要在表达式中描述定义切入点的方法<br/>* 表达式定义方式:采用注解方式的表达式或者Bean的方式<br/>* Bean方式:@Pointcut("bean(resourceController)")参数为bean名称* within方式:@Pointcut("within(com.jt.controller.ResourceController)")*/@Pointcut("@annotation(com.jt.annotations.RequiredLog)")public void doLog() {}
在需要执行日志拓展业务的方法添加标记注解
@Slf4j@RefreshScope@RestController@RequestMapping("/resource")public class ResourceController {@Value("${jt.resource.path:E:/images}")private String resourcePath;@Value("${jt.resource.host:http://localhost:8100/}")private String resourceHost;/*** 处理文件上传的请求<br/>* 其中@RequiredLog表示为切入点** @param uploadFile 接受要上传的文件数据,参数名需与客户端参数名一致* @return 文件上传后在服务器中的实际存储路径, 使用基于http协议访问此文件夹*/@RequiredLog("文件上传")@PostMapping("/upload")public String upLoadFile(MultipartFile uploadFile) throws IOException {//1.创建文件存储目录(使用年月日结构进行存储)String dateStr = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());//1.2创建文件上传对象File uploadDir = new File(resourcePath, dateStr);if (!uploadDir.exists()) {uploadDir.mkdirs();}//2.修改文件名称使其名称唯一String originalFilename = uploadFile.getOriginalFilename();//2.1构建文件前缀String filePrefix = UUID.randomUUID().toString();//2.2获取文件后缀String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));String newFileNme = filePrefix + fileSuffix;log.debug("新文件名为:" + newFileNme);//3.上传文件到指定目录uploadFile.transferTo(new File(uploadDir, newFileNme));//4.返回通过http协议可以访问到文件路径String accessAddress = resourceHost + dateStr + "/" + newFileNme;log.debug("上传地址为:{}",accessAddress);return accessAddress;}}
执行指定切入点的方法,进行拓展业务实现
@Slf4j@Component@Aspectpublic class LogAspect {/*** 在执行的切入点方法上执行@Around注解描述的方法** @param jp 连接点(期内封装所要执行的链信息,包括目标方法信息)* @return 目标方法的返回值*/@Around("doLog()")public Object doAround(ProceedingJoinPoint jp) throws Throwable {log.info("Around.Before:{}", System.currentTimeMillis());//执行目标执行链(包含切面,目标方法)Object result = jp.proceed();log.info("Around.After:{}", System.currentTimeMillis());return result;}}
