• 读取 resources 资源目录下的指定配置文件的值
    1. /**
    2. * 读取配置信息工具类
    3. */
    4. @Slf4j
    5. public class PropertiesUtil {
    6. private static Properties properties;
    7. static {
    8. String fileName = "demo.properties";
    9. properties = new Properties();
    10. try {
    11. properties.load(new InputStreamReader(
    12. Objects.requireNonNull(PropertiesUtil
    13. .class
    14. .getClassLoader()
    15. .getResourceAsStream(fileName),
    16. "当前配置文件不存在"), StandardCharsets.UTF_8));
    17. } catch (Exception e) {
    18. log.error("读取配置文件: {} 失败", fileName, e);
    19. }
    20. }
    21. /**
    22. * <h2>获取配置文件的值</h2>
    23. *
    24. * @param key 配置键
    25. * @return key 对应的值
    26. */
    27. public static String getProperty(String key) {
    28. if (Objects.isNull(key)) {
    29. return null;
    30. }
    31. String value = properties.getProperty(key.trim());
    32. if (Objects.isNull(value)) {
    33. return null;
    34. }
    35. return value.trim();
    36. }
    37. /**
    38. * <h2>获取配置文件的值</h2>
    39. *
    40. * @param key 配置键
    41. * @param defaultValue key不存在或者对应的值不存在,返回的默认值
    42. * @return key 对应的值
    43. */
    44. public static String getProperty(String key, String defaultValue) {
    45. if (Objects.isNull(key)) {
    46. return defaultValue;
    47. }
    48. String value = properties.getProperty(key.trim());
    49. if (Objects.isNull(value)) {
    50. return defaultValue;
    51. }
    52. return value.trim();
    53. }
    54. }