创建一个组件
AreaData
java">import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;/*** 初始化全局数据** @Package_Name * @Author * @TIME* @Version*/
@Component
public class AreaData implements CommandLineRunner {private static final Logger logger = LoggerFactory.getLogger(AreaData.class);@Autowiredprivate Service service;public static Map<String, String> map;@Overridepublic void run(String... args) {logger.info("***************开始加载数据***************");List<String> strings = service.query();map = strings.stream().collect(Collectors.toMap(e -> {String[] s = e.split("_");return s[s.length - 1];}, s -> s, (oldValue, newValue) -> oldValue));logger.info("***************结束加载数据***************");}
}
代码示意
map = strings.stream().collect(Collectors.toMap(e -> {
String[] s = e.split("_");
return s[s.length - 1];
}, s -> s, (oldValue, newValue) -> oldValue));
该段为 List<String> 转 Map<String, String>
toMap 中第三个参数为 出现重复 key 的处理方式:保留旧的
出现重复键会抛异常(非法状态异常):IllegalStateException
重点
@Component 注解不能忘
Leslie Lee 随笔