spring一些常用注解及其作用

@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请求 

常用的基本上就valuemethod了。其简化注解有

@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"))

猜你喜欢

转载自www.cnblogs.com/nxjblog/p/10612011.html