Spring-SpringMVC-SpringBoot注解

创建对象的

1
2
3
4
5
6
7
8
9
10
@Controller:放在类的上面,创建控制器对象,注入到容器中

@RestController:放在类的上面,创建控制对象,注入到容器中,使用这个注解类的,里面的控制器方法的返回值都是数据
@Controller@ResponseBody的复合注解

@Service:放在业务层的实现上面,创建Service对象,注入到容器中

@Repository:放在dao层的实现类上面,创建dao对象,放入到容器,没有使用这个注解是因为现在使用MyBatis框架,dao对象是MyBatis通过代理生成的,不需要Repository,所以没有使用

@Component:放在类的上面,创建此类的对象,放入容器中

赋值的

1
2
3
4
5
6
7
8
9
10
11
@Value:简单类型的赋值,例如在属性上面使用
@Value("李四")private String name
还可以使用@Value,获取配置文件的数量(properties或者yml)
@Value("${server.port}")private Interger port

@Autowired:引用类型赋值自动注入的,支持byName,byType,默认是byType,放在属性的上面,也可以放在构造方法的上面,推荐是放在构造方法上面

@Qualifer:给引用类型赋值,使用byName方式
@Autowired@Qualifer都是spring框架提供的

@Resource:来自jdk中的定义,实现引用类型的自动注入,支持byName,byType,默认是byName,如果byName失败,再使用byType注入,在属性上面使用

其他

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Configuration:放在类的上面,表示这是个配置类,相当于配置文件的作用

@Bean:放在方法的上面,把方法的返回值对象注入到spring容器中

@ImportResource:加载其他的xml配置文件,把文件中的对象注入到spring容器
@PropertySource:读取其他的properties属性配置文件
@ComponentScan:扫描器,指定包名,扫描注解
@ResponseBody:放在方法的上面,表示方法的返回值是数据,不是视图
@RequestBody:把请求体中的数据,读取出来,转为java对象使用
@ControllerAdvice:控制器增强,放在类上面,表示此类提供了方法,可以对Controller增加功能
@ExceptionHandler:处理异常的,放在方法的上面

@Transcational:处理事务的,放在service实现类的public方法上,表示此方法有事务


@SpringBootApplication:放在启动类的上面
包含了@SpringBootConfiguration @EnableAutoConfiguration,@ComponentScan

MyBatis相关注解:
@Mapper:放在类上面,让MyBatis找到接口,创建代理对象
@MapperScan:放在主类的上面,指定扫描的包,把这个包中所有接口创建代理对象,对象都注入到容器中
@Param:放在dao接口的方法的形参前面,作为命名参数使用的

Dubbo注解:
@DubboService:在提供者端使用的,暴露服务的,放在接口的实现类上面
@DubboReference:在消费者端使用的,引用远程服务,放在属性上面使用
@EnableDubbo:放在主类上面,表示当前引用启动Dubbo功能



请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@RequestMapping
Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。

派生请求: 处理get请求的映射 —> @GetMapping 请求指定的页面信息,并返回实体主体
处理post请求的映射 —> @PostMapping 向指定资源提交处理请求(例如提交表单或者上传文件)
处理put请求的映射 —> @PutMapping 更新
处理delete请求的映射 —> @DeleteMapping 删除
@RequestMapping(
value = {"/other","/other2","/other3"},
method = {RequestMethod.GET,RequestMethod.POST}
params = {"username=Keeling","password=123456"}
headers = {"Connection=keep-alive"}
)

* @RequestMapping的value属性:
@RequestMapping(“/other”)等价于@RequestMapping(value = “/other”)

* @RequestMapping的method属性:
method=RequestMethod.POST
* @RequestMapping的params属性:
1、“param”:表示要求请求映射所匹配的请求必须携带param请求参数
2、“!param”:表示要求请求映射所匹配的请求不能携带param请求参数
3、“param=value”:表示要求请求映射所匹配的请求必须携带param请求参数且param=value
4、“param!=value”:表示要求请求映射所匹配的请求必须携带param请求参数且param!=value
例如 params = {"username=Keeling","password=123456"}
访问localhost:8080/mvcDemo/other?username=Keeling&password=123456
* @RequestMapping的headers属性:

* REST风格
@RequestMapping("/other/{username}/{password}")
public String toPath(@PathVariable("username") String username,
@PathVariable("password") String password,
){
System.out.println("username="+username)
System.out.println("username="+password)
return "other";
}
访问localhost:8080/mvcDemo/other/Keeling/123456

swagger前后端分离

SpringBoot集成Swagger

1、新建SpringBoot项目,导入swagger依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!--swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

2、编写swagger的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Configuration
@EnableSwagger2
public class Swagger2Config {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean
public Docket coreApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(adminApiInfo())
.groupName("adminApi")
.select()
//只显示admin下面的路径
.paths(Predicates.and(PathSelectors.regex("/admin/.*")))
.build();
}

private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title("尚融宝后台管理系统--api文档")
.description("尚融宝后台管理系统接口描述")
.version("1.0")
.contact(new Contact("李燕茹","http://baidu.com","728831102@qq.com"))
.build();
}
}

3、添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函数的命名,通常需要自己增加一些说明来丰富文档内容。

Swagger使用的注解及其说明:

@Api:用在类上,说明该类的作用。
@ApiOperation:用在方法上。
@ApiParam:定义在参数上
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
l code:数字,例如400
l message:信息,例如”请求参数没填好”
l response:抛出异常的类

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

l @ApiModelProperty:描述一个model的属性

@ApiImplicitParams: 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//实体类
//entity的实体类中可以添加一些自定义设置
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="IntegralGrade对象", description="积分等级表")
public class IntegralGrade implements Serializable {

private static final long serialVersionUID = 1L;

@ApiModelProperty(value = "编号")
@TableId(value = "id", type = IdType.AUTO)
private Long id;

@ApiModelProperty(value = "积分区间开始")
private Integer integralStart;

@ApiModelProperty(value = "积分区间结束")
private Integer integralEnd;

@ApiModelProperty(value = "借款额度")
private BigDecimal borrowAmount;

@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;

@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;

@ApiModelProperty(value = "逻辑删除(1:已删除,0:未删除)")
@TableField("is_deleted")
@TableLogic
private Boolean deleted;
}
//controler层
@RestController
@RequestMapping("/admin/integralGrade")
@Api(value = "积分等级管理")
public class IntegralGradeController {

  @Resource
  private IntegralGradeService integralGradeService;

  @GetMapping("/list")
  @ApiOperation("积分等级列表")
  public Result listAll(){
      List<IntegralGrade> list = integralGradeService.list();
      return Result.ok().data("list",list);
  }

  @DeleteMapping("/remove/{id}")
  @ApiOperation(value = "根据id删除积分等级",notes = "逻辑删除")
  public Result removeById(
      @ApiParam(value = "数据id",required = true,example = "1")
      @PathVariable Long id){
      boolean result = integralGradeService.removeById(id);
      if (result){
          return Result.ok().message("删除成功");
      }else {
          return Result.error().message("删除失败");
      }
  }

  @PostMapping("/save")
  @ApiOperation(value = "新增积分等级")
  public Result save(@ApiParam(value = "积分等级对象",required = true) @RequestBody IntegralGrade integralGrade){
      boolean result = integralGradeService.save(integralGrade);
      if (result){
          return Result.ok().message("新增成功");
      }else {
          return Result.error().message("新增失败");
      }
  }

  @PutMapping("/updateById")
  @ApiOperation(value = "根据id修改积分等级")
  public Result updateById(@ApiParam(value = "积分等级对象",required = true) @RequestBody IntegralGrade integralGrade){
      boolean result = integralGradeService.updateById(integralGrade);
      if (result){
          return Result.ok().message("修改成功");
      }else {
          return Result.error().message("修改失败");
      }
  }

  @GetMapping("/getById/{id}")
  @ApiOperation(value = "根据id查询积分等级")
  public Result getById(@ApiParam(value = "数据id",required = true,example = "1") @PathVariable Long id){
      IntegralGrade result = integralGradeService.getById(id);
      if (result == null){
          return Result.error().message("查询失败");
      }else {
          return Result.ok().data("integralGrade",result);
      }
  }
  
}  

4.swagger只部署在测试环境,生产环境不部署(暴露接口容易被攻击)

参考:swagger使用教程 https://blog.csdn.net/YR_112233/article/details/122630446


觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭



wechat pay



alipay

Spring-SpringMVC-SpringBoot注解
http://yuting0907.github.io/2022/09/29/Spring-SpringMVC-SpringBoot注解/
作者
Echo Yu
发布于
2022年9月29日
许可协议