本文以 Spring Boot 应用、MySQL 数据库为例。
新建 DictionaryService.java、DictionaryServiceImpl.java,新增借口方法:addDictionaryToServletContext,用于调用加载字典到内存。
/**
* @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 方法,执行将字典加载到内存。
/**
* @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();
}
}