项目中需要在项目启动时把一些基础公共数据预加载到内存中,由于我们的基础数据是XML配置的方式,所以直接利用spring的注入,在配置文件中配置就可以了。
先是Java代码如下,采用map里面存map的形式:
public class PublicCode {
public static Map> codeMap = new HashMap>();
public Map> getCodeMap() {
return codeMap;
}
public static String getNameChn(String type, String key) {
return codeMap.get(type).get(key);
}
}
XML代码如下,
还有第二种方式,实现BeanPostProcessor 接口,这种方式适合从DB中读取一次性加载。下面实例仍然是从XML读取:
public class CommonCodeBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if(bean instanceof CommonCode) {
((CommonCode)bean).loadMap();
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
}
public class CommonCode {
public static final String NAME = "name";
public static final String KEY = "key";
public static final String VALUE = "value";
public static final Map MAP = new HashMap();
private Resource resourceXML;
public CommonCode() {
}
public void loadMap() {
Assert.notNull(resourceXML,"resourceXML must be not null");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(resourceXML.getInputStream());
Element root = doc.getDocumentElement();
if (root == null) {
return;
}
NodeList codeNodeList = root.getChildNodes();
String name = null;
for (int i=0; i < codeNodeList.getLength(); i++) {
Node node = (Node) codeNodeList.item(i);
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
name = node.getAttributes().getNamedItem(NAME).getNodeValue();
Map m = null;
if (!MAP.containsKey(name)) {
m = new HashMap();
MAP.put(name, m);
} else {
m = (Map) MAP.get(name);
}
NodeList keyValues = node.getChildNodes();
for (int j=0; j < keyValues.getLength(); j++) {
Node key = (Node)keyValues.item(j);
if (key != null && key.getNodeType() == Node.ELEMENT_NODE) {
m.put(key.getAttributes().getNamedItem(KEY).getNodeValue(), key.getAttributes().getNamedItem(VALUE).getNodeValue());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Resource getResourceXML() {
return resourceXML;
}
public void setResourceXML(Resource resourceXML) {
this.resourceXML = resourceXML;
}
}
Spring配置如下:
CommonCode.xml: