1. 注意事項
package com.jayce.boot.route.component.mock;
import io.swagger.annotations.ApiModelProperty;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MockData {
@ApiModelProperty("模拟值key")
String key() default "";
}
2. セクション
package com.jayce.boot.route.component.mock;
import com.jayce.boot.route.common.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Slf4j
@Aspect
@Component
public class MockAspect {
@Pointcut("@annotation(com.jayce.boot.route.component.mock.MockData)")
public void pointCut() {
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
//用的最多通知的签名
Signature signature = joinPoint.getSignature();
MethodSignature msg=(MethodSignature) signature;
Object target = joinPoint.getTarget();
//获取注解标注的方法
Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
//通过方法获取注解
MockData mockData = method.getAnnotation(MockData.class);
String key = mockData.key();
MockService mockService = SpringUtil.getBean(MockService.class);
Object mockValue = mockService.getMockValue(key);
return mockValue;
}
}
3. アナログデータクラス
package com.jayce.boot.route.component.mock;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jayce.boot.route.common.util.PageUtil;
import com.jayce.boot.route.entity.LibraryBook;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MockService {
/**
* 获取mock数据
*
* @param key key
* @return java.lang.String
*/
public Object getMockValue(String key) {
Map<String, Object> map = new HashMap<>();
map.put("key1", "{1,2,3}");
PageInfo<LibraryBook> testPage = new PageInfo<>();
List<LibraryBook> list = Lists.newArrayList(LibraryBook.builder()
.bookId(1L)
.bookName("HerryPoter")
.build());
testPage = PageUtil.build(list, 10, 1, 10);
map.put("testPage", testPage);
return map.get(key);
}
}