1.
.新建一個類 繼承 RequestMappingHandlerMapping
package com.boot.missyou.core.hack; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.lang.reflect.Method; public class AutpPrefixMapping extends RequestMappingHandlerMapping { @Value("${missyou.api-package}") private String packagePath; @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo reinfo = super.getMappingForMethod(method, handlerType); if (reinfo!=null) { String prefix = this.getPrefix(handlerType);
// 替換並且合並為新路徑 RequestMappingInfo newrequestMappingInfo =RequestMappingInfo.paths(prefix).build().combine(reinfo); return newrequestMappingInfo; } return reinfo; }
// 獲取前綴 public String getPrefix(Class<?> handlerType) { String packName = handlerType.getPackage().getName(); String doPath = packName.replaceAll(this.packagePath, ""); return doPath.replace(".","/"); } }
2.重新一個類讓容器發現 AutpPrefixMapping 類
采用
@Component + 繼承 WebMvcRegistrations
package com.boot.missyou.core.congiguration; import com.boot.missyou.core.hack.AutpPrefixMapping; import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations; import org.springframework.stereotype.Component; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @Component public class AutoPrefixConfigration implements WebMvcRegistrations { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new AutpPrefixMapping(); } }
3. 添加配置 屬性
application.properties
missyou.api-package = com.boot.missyou.api
為了 可以在類中訪問到
4.添加 controller
package com.boot.missyou.api.v1; import com.boot.missyou.exception.http.ForbiddenException; import com.boot.missyou.service.BannerService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Api(value = "輪播圖", tags = {"用於輪播圖的相關接口"}) @RestController @RequestMapping("/banner") public class BannerController { @Autowired private BannerService bannerService; @ApiOperation(value = "輪播圖", notes = "輪播圖", httpMethod = "GET") @GetMapping("/test") public String test() { throw new ForbiddenException(1001); // return "hell cworld111333"; } }
這個controller位於 v1 的包下
5.測試