SpringBoot

SpringBoot

分组校验

  1. 实体类中创建接口(为空,用于连接实体类以及接口)
  2. 在字段上对不同接口进行分别验证
  3. Controller中对参数开启指定接口验证
1
public Result updateDevice(@RequestBody @Validated(value = Device.UpdateDevice.class) Device device) throws ParseException {
1
2
3
4
5
6
7
8
9
public interface InsertDevice {
}

public interface UpdateDevice {
}

@NotNull(message = "设备ID不能为空", groups = {UpdateDevice.class})
@ApiModelProperty("设备ID")
private Integer id;

实体类使用引用类型

由于java中的基本类型会有默认值,例如当某个类中存在private int age;字段时,创建这个类时,age会有默认值0.当使用age属性时,它总会有值。因此,在某些情况下,便无法使age为null.并且在动态SQL的部分,如果使用age != null 进行判断,结果总会为true,会导致很多隐藏的问题。

所以,在实体类中不要使用基本类型。基本类型包括 byte\short\int\long\float\double\char\boolean.

结论:在mybatis中,不要使用基本类型,要使用引用类型。

统一处理权限返回值

1
2
3
4
5
6
7
8
9
10
11
@ControllerAdvice
public class UnauthorizedAdvice {

@ResponseBody
@ExceptionHandler(AuthorizationException.class)
public Result AuthorizationException(Exception ex) {
// 登录了 但是操作权限没有
return new Result(ResultCode.UNAUTHENTICATED_OPERATION);
}

}

@postConstruct

  • 注解使用在方法上,表示该方法在实例化当前Bean后立刻执行该方法,再去实例化其他Bean
  • 可以有多个@PostConstruct方法

做初始化工作

ResponseEntity.ok(execute)

1
2
3
4
5
6
7
@GetMapping("/lua")
public ResponseEntity lua() {
List<String> keys = Arrays.asList("testLua", "hello lua");
Boolean execute = stringRedisTemplate.execute(redisScript, keys, "100","200");
assert execute != null;
return ResponseEntity.ok(execute);
}

返回ok

ClassPathResource

1
2
3
4
5
6
7
@Bean
public DefaultRedisScript<Boolean> redisScript() {
DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("\\script\\firstLua.lua")));
redisScript.setResultType(Boolean.class);
return redisScript;
}

ClassPathResource直接在resources包下,路径打后面的就可以