Java启动工程时,加载固定数据到Map中(不用每次访问数据库)

时间:2022-12-06 08:08:58

如下:启动工程时,加载配置文件的用户名和密码到map中,

通过getKeyByValue()获取即可

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component; @Component
public class PersonalInfoCache { private static Map<String,String> map = new HashMap<String,String>(); @PostConstruct
public void initCache() {
PropertiesLoadUtil propertiesUtil = new PropertiesLoadUtil("commons-config.properties");
String userName = propertiesUtil.getStringProperty("userName");
String password = propertiesUtil.getStringProperty("password");
map.put("userName", userName);
map.put("password", password);
} public String getKeyByValue(String key){
if(StringUtils.isEmpty(key)){
return null;
}
for(Entry<String,String> entry:map.entrySet()){
if(entry.getKey().equals(key)){
return entry.getValue();
}
}
return null;
} }

PropertiesLoadUtil 工具类地址:

https://www.cnblogs.com/Donnnnnn/p/9237443.html