McConf.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package com.malk.server.common;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.data.domain.PageRequest;
  5. import org.springframework.stereotype.Component;
  6. import javax.annotation.Nullable;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Optional;
  10. /**
  11. * 读取配置文件
  12. *
  13. * @Value("${ }") :变量读取方式,尤其注意不支持读取yml文件内容,可通过在变量后 :10 设置默认值为 10
  14. * 添加的属性前,为该字段赋值:@Value("${dingding.appKey}"
  15. * 需要3个前提: 不能使用static或final修饰了tagValue; 类没有加上@Component(或者@service等); 类被new新建了实例,而没有使用@Autowire
  16. * * --------------------------------------------------------------------------------- *
  17. * @ConfigurationProperties(prefix = "pre") 对象读取方式: 实例化承载对象
  18. * 将指定前缀配置实例化为实体类 [添加 spring-boot-configuration-processor依赖避免idea报错]
  19. * 尤其注意: 需要为类添加组件注解, 如 @Service, @Component, ...; 引用实体类必须通过 @Autowired 进行注入, 否则识别到为空 [使用注意与 @Value 相同]
  20. */
  21. @Data
  22. @Component
  23. @ConfigurationProperties(prefix = "corp")
  24. public class McConf {
  25. private int timeOut;
  26. private int timeAwait;
  27. private List<String> engineers;
  28. /**
  29. * 最大分页
  30. */
  31. public static int pageSize = 100;
  32. /**
  33. * 分页数据
  34. */
  35. public static PageRequest simplePage(@Nullable Map param) {
  36. int page = Integer.parseInt(String.valueOf(Optional.ofNullable(param.get("page")).orElse("1")));
  37. int size = Integer.parseInt(String.valueOf(Optional.ofNullable(param.get("size")).orElse(pageSize)));
  38. page -= 1;
  39. if (page < 0) {
  40. page = 0;
  41. }
  42. if (size > pageSize) {
  43. size = pageSize;
  44. }
  45. if (size < 1) {
  46. size = 1;
  47. }
  48. return PageRequest.of(page, size);
  49. }
  50. /**
  51. * 全部数据
  52. */
  53. public static PageRequest allDataPage() {
  54. return PageRequest.of(0, Integer.MAX_VALUE);
  55. }
  56. /**
  57. * 单条数据
  58. */
  59. public static PageRequest singleDataPage() {
  60. return PageRequest.of(0, 1);
  61. }
  62. /**
  63. * 简单分页: 先查询再分页, 用于数据组装场景
  64. */
  65. public static List manualPage(PageRequest pageRequest, List dataList) {
  66. long total = dataList.size();
  67. if (pageRequest.getPageSize() < total) {
  68. int start = pageRequest.getPageNumber() * pageRequest.getPageSize();
  69. if (start > total) start = (int) total;
  70. int end = (pageRequest.getPageNumber() + 1) * pageRequest.getPageSize();
  71. if (end > total) end = (int) total;
  72. dataList = dataList.subList(start, end);
  73. }
  74. return dataList;
  75. }
  76. }