通過spring獲取properties檔案屬性值
阿新 • • 發佈:2019-02-03
首先貼一下傳統用法和@Value註解的用法示例:
上面這篇部落格裡介紹了通過xml方式和註解方式獲取properties屬性的方法,通常看完這篇部落格就已經可以解決大部分情況了。但是有一種極端的情況就是你的專案裡沒有applicationContext.xml檔案。這時候你需要獲取配置怎麼辦呢?直接先上程式碼
import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.util.Properties; @Slf4j public class CountTaskService { public static void main(String[] args) throws Exception{ Resource resource = new ClassPathResource("/task.properties"); Properties properties = PropertiesLoaderUtils.loadProperties(resource); Object o = properties.get("countOnlineUser.perfix"); log.info(o.toString()); } }
執行示例如下:
專案目錄結構如下:
properties配置如下:
如果有多個檔案,在程式碼裡讀取多個就可以了,如果不在resources這一級目錄下,記得帶上目錄