SpringBoot + 指定包下所有控制器 + 添加统一前缀
自定义版本控制器接口定义
提供两个方法,一个方法是需要添加url前缀的控制器所属的包名称,一个是需要添加的url前缀。
/**
* 版本控制器
*
* @author Hanqi <jpanda@aliyun.com>
* @since 2019/3/13 16:11
*/
public interface VersionHandler {
/**
* 需要处理的控制器所处的包名
*/
String getPackageName();
/**
* 需要添加的前缀
*/
String getPrefix();
}
简单的版本控制器实现
import org.springframework.stereotype.Component;
/**
* 版本控制实例
* @author Hanqi <jpanda@aliyun.com>
* @since 2019/3/13 16:11
*/
@Component
public class TwoVersionHandler implements VersionHandler {
@Override
public String getPackageName() {
return "com.uustore.uustoreapi.controller";
}
@Override
public String getPrefix() {
return "v2";
}
}
实现添加url前缀核心方法的请求映射处理器
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class VersionControlRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
protected Set<VersionHandler> versionHandlers;
protected boolean hasVersionHandler = false;
@Override
public void afterPropertiesSet() {
// 初始化版本控制器类型集合
initVersionHandlers();
super.afterPropertiesSet();
}
@Override
protected void initHandlerMethods() {
super.initHandlerMethods();
}
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo info = super.getMappingForMethod(method, handlerType);
if (info != null) {
final String packageName = handlerType.getPackage().getName();
for (VersionHandler versionHandler : versionHandlers) {
if (packageName.startsWith(versionHandler.getPackageName())) {
RequestMappingInfo versionInfo = buildRequestMappingInfo(versionHandler.getPrefix());
info = versionInfo.combine(info);
return info;
}
}
}
return info;
}
protected void initVersionHandlers() {
versionHandlers = new HashSet<>(obtainApplicationContext().getBeansOfType(VersionHandler.class).values());
hasVersionHandler = !CollectionUtils.isEmpty(versionHandlers);
}
protected RequestMappingInfo buildRequestMappingInfo(String path) {
return RequestMappingInfo.paths(path).build();
}
}
注册使用自定义的请求映射处理器
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/**
* 配置使用自定义版本url处理器
*
* @author Hanqi <jpanda@aliyun.com>
* @since 2019/3/13 16:11
*/
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class VersionControlWebMvcConfiguration implements WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new VersionControlRequestMappingHandlerMapping();
}
}
网友评论