自定义@RestController用以简化与@RequestMapping的联合使用场景

版权声明:原创欢迎转载,转载请注明出处 https://blog.csdn.net/ye17186/article/details/88170264

在实际开发中,我们经常使用@RestController/@Controller+@RequestMapping来标注一个Controller

@RestController
@RequestMapping("/test")
public class TestController {
    ...
}

在这里,每次都需要开发者写两个注解,比较麻烦。下面就对它进行自定义封装,以后只需要写一个注解就能达到同样的效果。

新建一个注解类:YRestController

/**
 * 自定义RestController注解,结合RequestMapping
 *
 * @author ye17186
 * @version 2019/3/5 10:22
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
@RequestMapping
public @interface YRestController {

    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};
}

封装之后,我们再写Controller时,就可以少一行代码了

@YRestController("/test")
public class TestController {
    ...
}

上面是@RestController封装,@Controller的封装只需要把YRestController中的@RestController替换成@Controller即可,一看就懂。

GitHub地址:https://github.com/ye17186/spring-boot-learn

猜你喜欢

转载自blog.csdn.net/ye17186/article/details/88170264