SpringBoot中的一些註解總結
阿新 • • 發佈:2019-01-22
1:@RestController
那麼這個註解和@Controller有什麼區別? 嗯哼,事情開始變得有意思起來了1. Controller, RestController的共同點
都是用來表示spring某個類的是否可以接收HTTP請求
2. Controller, RestController的不同點
@Controller標識一個Spring類是Spring MVC controller處理器
@RestController: @RestController是@Controller和@ResponseBody的結合體,兩個標註合併起來的作用。
下面是@RestController的原始碼,看了之後你會更清晰的看出來他們之間的區別這裡需要注意一點:當你在springboot中使用模板模式返回一個字串去匹配對應的頁面的時候,方法所在的類是不能使用@RestController而應該使用@Controller,為什麼?看上面。當然,如果http請求是通過ajax傳送到服務端,還是要使用@RestController註解的。* Copyright 2002-2016 the original author or authors. package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.stereotype.Controller; /** * A convenience annotation that is itself annotated with * {@link Controller @Controller} and {@link ResponseBody @ResponseBody}. * <p> * Types that carry this annotation are treated as controllers where * {@link RequestMapping @RequestMapping} methods assume * {@link ResponseBody @ResponseBody} semantics by default. * * <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate * {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the * {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter} * pair which are the default in the MVC Java config and the MVC namespace. * In particular {@code @RestController} is not supported with the * {@code DefaultAnnotationHandlerMapping}-{@code AnnotationMethodHandlerAdapter} * pair both of which are also deprecated. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 4.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any * @since 4.0.1 */ String value() default ""; }