SpringBoot2為接口統(tǒng)一加url前綴的實現(xiàn)示例
背景
有時候會面臨前后端都放在一起的情況,這個時候我們就不好去使用配置中的 server.servlet.context-path ,經(jīng)過一番查找,發(fā)現(xiàn)使用注解還是挺方便的。
解決辦法
定義注解
package com.example.demo.annotation;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import java.lang.annotation.*;
/**
* controller層統(tǒng)一使用該注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
public @interface ApiRestController {
/**
* Alias for {@link Controller#value}.
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
實現(xiàn)WebMvcConfigurer配置路徑前綴
package com.example.demo.config;
import com.example.demo.annotation.ApiRestController;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置統(tǒng)一的后臺接口訪問路徑的前綴
*/
@Configuration
public class CustomWebMvcConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer
.addPathPrefix("/api", c -> c.isAnnotationPresent(ApiRestController.class));
}
}
在Controller類上使用注解
package com.example.demo.controller.api;
import com.example.demo.annotation.ApiRestController;
import org.springframework.web.bind.annotation.GetMapping;
@ApiRestController
@RequestMapping("/token")
public class UserTokenController {
/**
* 獲取 user token
*/
@GetMapping("/getUserToken")
public ResponseBase getUserToken(HttpServletRequest request, HttpServletResponse response){
}
}
到此這篇關(guān)于SpringBoot2為接口統(tǒng)一加url前綴的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot2 接口統(tǒng)一加url前綴內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解MyBatis直接執(zhí)行SQL查詢及數(shù)據(jù)批量插入
這篇文章主要介紹了MyBatis直接執(zhí)行SQL查詢及數(shù)據(jù)批量插入的相關(guān)知識,需要的朋友一起學習吧2016-01-01
util.Date與sql.Date的相互轉(zhuǎn)換過程
本文介紹了Java中兩個常用日期類的區(qū)別和相互轉(zhuǎn)換方法,包括java.util.Date和java.sql.Date,并展示了如何使用SimpleDateFormat進行日期格式化2026-01-01
JSON復雜數(shù)據(jù)處理之Json樹形結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)Java對象并存儲到數(shù)據(jù)庫的實現(xiàn)
這篇文章主要介紹了JSON復雜數(shù)據(jù)處理之Json樹形結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)Java對象并存儲到數(shù)據(jù)庫的實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2016-03-03

