Spring Boot自定义参数处理实体ID

Spring Boot自定义参数处理实体ID

在实际业务中经常需要判断接收的实体ID是否在表中存在和向线程中注入该实体ID对应的数据,下面摘录了两种思路:

实现Converter来获取主键ID

1
2
3
4
5
6
7
8
9
10
@RestController
class GitRepositoryController {

@GetMapping("/repositories/{repoId}")
String getSomething(@PathVariable("repoId") GitRepositoryId repositoryId) {
// ... load and return repository
}

}

1
2
3
4
5
6
7
8
9
@Value
class GitRepositoryId {
private final long value;

public static GitRepositoryId valueOf(String value){
return new GitRepositoryId(Long.parseLong(value));
}
}

1
2
3
4
5
6
7
8
9
10
@Component
class GitRepositoryIdConverter implements Converter<String, GitRepositoryId> {

@Override
public GitRepositoryId convert(String source) {
// TODO 这里可以增加 exist 检测 和 在线程上下文中注入实体信息
return new GitRepositoryId(Long.parseLong(source));
}
}

实现 HandlerMethodArgumentResolver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@RequiredArgsConstructor
class GitRepositoryArgumentResolver implements HandlerMethodArgumentResolver {

private final GitRepositoryFinder repositoryFinder;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameter().getType() == GitRepository.class;
}

@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) {

String requestPath = ((ServletWebRequest) webRequest)
.getRequest()
.getPathInfo();

String slug = requestPath
.substring(0, requestPath.indexOf("/", 1))
.replaceAll("^/", "");

return gitRepositoryFinder.findBySlug(slug)
.orElseThrow(NotFoundException::new);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
@RequiredArgsConstructor
class GitRepositoryArgumentResolverConfiguration implements WebMvcConfigurer {

private final GitRepositoryFinder repositoryFinder;

@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new GitRepositoryArgumentResolver(repositoryFinder));
}

}

REF