@Controller 處理http請求的控制器
例子:
@Controller public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } }
@RestController
Spring4之后新加入的注解,原來返回json需要@ResponseBody和@Controller配合。
即@RestController是@ResponseBody和@Controller的組合注解。
例子:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } }
@RequestMapping 配置url映射
@RequestMapping此注解即可以作用在控制器的某個方法上,也可以作用在此控制器類上;@RequestMapping中的method參數有很多中選擇,一般使用get/post.
當控制器在類級別上添加@RequestMapping注解時,這個注解會應用到控制器的所有處理器方法上。處理器方法上的@RequestMapping注解會對類級別上的@RequestMapping的聲明進行補充。
@RequestMapping(value="/queryById") 普通請求 @RequestMapping(value="/hello",method= RequestMethod.GET) get請求 @RequestMapping(value="/hello",method= RequestMethod.POST) post請求
常用的基本上就value
和method
了。其簡化注解有
@GetMapping 等同於 @RequestMapping(method = RequestMethod.GET)
@PostMapping 等同於 @RequestMapping(method = RequestMethod.POST)
@PutMapping 等同於 @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping 等同於 @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping 等同於 @RequestMapping(method = RequestMethod.PATCH)
一些其他注釋:
Spring 來掃描指定包下的類,並注冊被@Component,@Controller,@Service,@Repository等注解標記的組件
- @Component 最普通的組件,可以被注入到spring容器進行管理
- @Repository 作用於持久層
- @Service 作用於業務邏輯層@Resource(這個注解屬於J2EE的),默認安照名稱進行裝配,名稱可以通過name屬性進行指定
- @Resource(這個注解屬於J2EE的),默認安照名稱進行裝配,名稱可以通過name屬性進行指定(例:@Resource(name="userService"))