springboot 專案框架搭建(三):工具類中讀取配置檔案
阿新 • • 發佈:2018-12-21
一.原因
編寫一個服務類的工具類,想做成一個靈活的配置,各種唯一code想從配置檔案中讀取,便有了這個坑。
二.使用@value獲取值為null,
這是因為這個工具類沒有交給spring boot 來管理,導致每次都是new 一個新的,所以每次取出來的值都是nu l l
三.解決
方式一
springboot 中ResourceBundle 載入配置檔案 報java.util.MissingResourceException: Can't find bundle for base name config/application.properties, locale zh_CN
如果帶有後綴properties 則從專案根路徑查詢,去掉字尾則預設是classpath下查詢。修改成如下則正常通過
//這裡使用@value,取不到properties中的值,使用工具類來讀取 private final static ResourceBundle resourceBundle = ResourceBundle.getBundle("application"); //轉換座標所需要的配置資訊 private final static String ak = resourceBundle.getString("geohey.ak"); private final static String centroidurl = resourceBundle.getString("geohey.centroidurl"); private final static String areaurl = resourceBundle.getString("geohey.areaurl"); private final static String insr = resourceBundle.getString("geohey.insr"); private final static String measuresr = resourceBundle.getString("geohey.measuresr");
方式二,交給spring管理
@Autowired
private MapCenterPointUtil MapCenterPointUtil;
@Component
public class MapCenterPointUtil {
@Value("${geohey.ak}")
private String ak = resourceBundle.getString("");
}