一、声明bean的注解(IOC)
- @Controller/RestController 标记在表现层,接受请求,响应数据
- @Component
- @Service 标记在业务层,逻辑处理
- @Repository 标记在持久层,数据访问
- 以上用于组件扫描 - 启动类扫描的时当前包及其子包
- @SprinhBootApplication 标记在启动类/引导类上 用来扫描当前包和其子包。
二、DI依赖注入注解
- @Autowried 默认根据类型注入,spring提供
- 同类型下多个bean可以使用以下注解。
- @Resource(name="")默认根据名称来注入,JDK提供。
- @Primary
- @Autowried+@Qualifier("")
三、其他注解
-
@Resposebody 将方法的返回值直接返回给前端,如果返回值是一个对象或集合,那将先转为json在响应。
-
请求参数
- @RequestParam("") 将前端传来的请求参数当做形参传给方法;如果前端传递的请求参数名与方法参数名一致可以省略不写。
- @RequestBady 将前端传来的json格式的对象或集合封装到对象中去。
- @PathVariable 获取路径变量
// @@RequestParam 属性用法
@DeleteMapping
public Result deptDelete(@RequestParam(name = "id") Integer id) {
log.warn("DeptController deptDelete {}",id);
// 调用业务层
deptService.deptDelete(id);
return Result.success();
}
// @RequestBady 属性用法
@PostMapping
public Result deptInsert(@RequestBody Dept dept) {
log.warn("DeptController deptInsert {}",dept);
// 调用业务层
deptService.deptInsert(dept);
return Result.success();
}
```
//@PathVariable 属性用法
@GetMapping( "{id}")
public Result deptSelectById(@PathVariable Integer id){
log.warn("DeptController deptSelectById {}",id);
// 调用业务层
Dept dept = deptService.deptFindById(id);
return Result.success(dept);
}
- 请求路径
- @RequestMapping 可以在类上,也可以在方法上
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
@RequestMapping("/depts")
@RestController
@Slf4j
public class DeptController {
@Autowired
private DeptService deptService; //部门业务接口
/*
查询部门列表
* */
@GetMapping
public Result deptSelect(){
log.warn("DeptController deptSelect");
// 调用业务层
List<Dept> depts = deptService.findAll();
return Result.success(depts);
}
/*
根据id删除数据
* */
@DeleteMapping
public Result deptDelete(Integer id) {
log.warn("DeptController deptDelete {}",id);
// 调用业务层
deptService.deptDelete(id);
return Result.success();
}
/*
新增数据
* */
@PostMapping
public Result deptInsert(@RequestBody Dept dept) {
log.warn("DeptController deptInsert {}",dept);
// 调用业务层
deptService.deptInsert(dept);
return Result.success();
}
/*
* 修改数据
* */
@PutMapping
public Result deptUpdata(@RequestBody Dept dept) {
log.warn("DeptController deptUpdata {}",dept);
// 调用业务层
deptService.deptUpdata(dept);
return Result.success();
}