通常情况下,通过@RequestMapping注解来完成请求映射,我们也可以通过WebMvcConfigurer来修改请求映射。
示例:
将带@Anno注解的controller的路径映射加上/anno前缀,
一、注解定义:
package com.example.anno;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
}
二、controller定义,加上@MyAnno注解:
package com.example.controller;
import com.example.anno.MyAnno;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@MyAnno
public class AnnoController {
@RequestMapping("/my")
public String getAnno(){
return "this is annotation!";
}
}
三、配置WebMvcConfigurer
package com.example.config;
import com.example.anno.MyAnno;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfig {
@Bean
WebMvcConfigurerAdapter getWebMvcConfigurer(){
return new WebMvcConfigurerAdapter() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer){
configurer.addPathPrefix("anno",c -> c.isAnnotationPresent(MyAnno.class));
}
};
}
}
四、访问请求:
ip:port/anno/my