Java 数据字典设计之加载字典到内存(二)

本文以 Spring Boot 应用、MySQL 数据库为例。 新建 DictionaryService.java、DictionaryServiceImpl.java,新增借口方法:addDictionaryToServletContext,用于调用加载字典到内存。

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
39
40
41
42
43
44
45
46
47
/**
* @author godcheese
*/
@Service
public class DictionaryServiceImpl implements DictionaryService {

@Autowired
private DictionaryMapper dictionaryMapper;

@Autowired
private WebApplicationContext webApplicationContext;

private static final Logger LOGGER = LoggerFactory.getLogger(DictionaryServiceImpl.class);

@Override
public void addDictionaryToServletContext() {
ServletContext servletContext = webApplicationContext.getServletContext();
if (servletContext != null) {

List<DictionaryEntity> dictionaryEntityList = dictionaryMapper.listAll();
for (DictionaryEntity dictionaryEntity : dictionaryEntityList) {
servletContext.setAttribute(dictionaryEntity.getKey().toUpperCase() + "." + dictionaryEntity.getValueSlug().toUpperCase(), dictionaryEntity.getValue());
}

Map<String, List<DictionaryEntity>> dictionaryEntityMap = new HashMap<>(6);
for (DictionaryEntity dictionaryEntity : dictionaryEntityList) {
String key = dictionaryEntity.getKey().toUpperCase();
if (dictionaryEntityMap.containsKey(key)) {
List<DictionaryEntity> dictionaryEntityList1 = dictionaryEntityMap.get(key);
if (!dictionaryEntityList1.contains(dictionaryEntity)) {
dictionaryEntityList1.add(dictionaryEntity);
dictionaryEntityMap.put(key, dictionaryEntityList1);
}
} else {
List<DictionaryEntity> dictionaryEntityList2 = new ArrayList<>(1);
dictionaryEntityList2.add(dictionaryEntity);
dictionaryEntityMap.put(key, dictionaryEntityList2);
}
}

for (Map.Entry entry : dictionaryEntityMap.entrySet()) {
servletContext.setAttribute((String) entry.getKey(), entry.getValue());
}

}
}
}

新建 ApplicationStartupRunner.java,用于程序启动时进行的操作,此处调用 DictionaryService 的 addDictionaryToServletContext 方法,执行将字典加载到内存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @author godcheese
* @date 2018/2/22 16:19
*/
@Component
@Order
public class ApplicationStartupRunner implements CommandLineRunner {

private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationStartupRunner.class);

@Autowired
private DictionaryService dictionaryService;

@Override
public void run(String... strings) throws Exception {

// 首次启动加载数据字典到 ServletContext 内存
dictionaryService.addDictionaryToServletContext();

}
}