0

I have defined an ApiController to add a prefix (/api) to route match. I am using Spring Boot

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@RestController
@RequestMapping("/api")
public @interface ApiController {

    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value();

}

and Use in the controller like

@ApiController("/user")
public class UserController {

    /**
     * Define url methods
     *
     */
}

but I don't know why /api/user/ not serving. it serve at /user/ Endpoint. Can any one know the exact error ?

2 Answers2

1

When you use @AliasFor, it means that the property of your annotation is an alias for the property from another annotation. In your example, ApiController.value is an alias for RequestMapping.value and when you set ApiController.value, the same value set to RequestMapping.value. Not adding or concatenating, just set the new value. You can read how @AliasFor work here

What about your issue. As I understand you want to set api root url. You can do it with one of the way from this question. Please note that in Option 2, the same technic is used, but there is not used @AliasFor for overriding/extending RequestMapping.value.

Maxim Popov
  • 1,167
  • 5
  • 9
1

I am explaining below, How I solve the problem after checking the Implementation of @RestController.

I create a Alias for RestController as

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
public @interface ApiController {

    @AliasFor(
            annotation = RestController.class
    )
    String value() default "";
}

and then I create a configuration to add the prefix.

@Configuration
public class Config implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(ApiController.class));
    }
}

and its works for me.