package com.malk.server.common; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import java.util.List; import java.util.Map; import java.util.Optional; /** * 读取配置文件 * * @Value("${ }") :变量读取方式,尤其注意不支持读取yml文件内容,可通过在变量后 :10 设置默认值为 10 * 添加的属性前,为该字段赋值:@Value("${dingding.appKey}" * 需要3个前提: 不能使用static或final修饰了tagValue; 类没有加上@Component(或者@service等); 类被new新建了实例,而没有使用@Autowire * * --------------------------------------------------------------------------------- * * @ConfigurationProperties(prefix = "pre") 对象读取方式: 实例化承载对象 * 将指定前缀配置实例化为实体类 [添加 spring-boot-configuration-processor依赖避免idea报错] * 尤其注意: 需要为类添加组件注解, 如 @Service, @Component, ...; 引用实体类必须通过 @Autowired 进行注入, 否则识别到为空 [使用注意与 @Value 相同] */ @Data @Component @ConfigurationProperties(prefix = "corp") public class McConf { private int timeOut; private int timeAwait; private List engineers; /** * 最大分页 */ public static int pageSize = 100; /** * 分页数据 */ public static PageRequest simplePage(@Nullable Map param) { int page = Integer.parseInt(String.valueOf(Optional.ofNullable(param.get("page")).orElse("1"))); int size = Integer.parseInt(String.valueOf(Optional.ofNullable(param.get("size")).orElse(pageSize))); page -= 1; if (page < 0) { page = 0; } if (size > pageSize) { size = pageSize; } if (size < 1) { size = 1; } return PageRequest.of(page, size); } /** * 全部数据 */ public static PageRequest allDataPage() { return PageRequest.of(0, Integer.MAX_VALUE); } /** * 单条数据 */ public static PageRequest singleDataPage() { return PageRequest.of(0, 1); } /** * 简单分页: 先查询再分页, 用于数据组装场景 */ public static List manualPage(PageRequest pageRequest, List dataList) { long total = dataList.size(); if (pageRequest.getPageSize() < total) { int start = pageRequest.getPageNumber() * pageRequest.getPageSize(); if (start > total) start = (int) total; int end = (pageRequest.getPageNumber() + 1) * pageRequest.getPageSize(); if (end > total) end = (int) total; dataList = dataList.subList(start, end); } return dataList; } }