1、获取配置文件信息-工具类

  1. /**
  2. * 获取配置文件信息
  3. */
  4. @Component
  5. @Slf4j
  6. public class PropertiesUtil {
  7. //key需要根据不同需求做调整
  8. public static final byte[] KEY = { 9, -1, 0, 5, 39, 8, 6, 19 };
  9. private static Environment env;
  10. @Autowired
  11. protected void set(Environment env) throws IOException {
  12. PropertiesUtil.env = env;
  13. }
  14. /**
  15. * Get a value based on key , if key does not exist , null is returned
  16. *
  17. * @param key
  18. * @return
  19. */
  20. public static String getProperty(String key) {
  21. try {
  22. return env.getProperty(key);
  23. } catch (MissingResourceException e) {
  24. return null;
  25. }
  26. }
  27. /**
  28. * Get a value based on key , if key does not exist , null is returned
  29. *
  30. * @param key
  31. * @return
  32. */
  33. public static String getProperty(String key, String defaultValue) {
  34. try {
  35. String value = env.getProperty(key);
  36. if (StringUtils.isEmpty(value)) {
  37. return defaultValue;
  38. }
  39. return value;
  40. } catch (MissingResourceException e) {
  41. return defaultValue;
  42. }
  43. }
  44. /**
  45. * 根据key获取值
  46. *
  47. * @param key
  48. * @return
  49. */
  50. public static int getInt(String key) {
  51. return Integer.parseInt(env.getProperty(key));
  52. }
  53. /**
  54. * 根据key获取值
  55. *
  56. * @param key
  57. * @param defaultValue
  58. * @return
  59. */
  60. public static int getProperty(String key, int defaultValue) {
  61. String value = env.getProperty(key);
  62. if (StringUtils.isBlank(value)) {
  63. return defaultValue;
  64. }
  65. return Integer.parseInt(value);
  66. }
  67. /**
  68. * 根据key获取值
  69. *
  70. * @param key
  71. * @param defaultValue
  72. * @return
  73. */
  74. public static boolean getProperty(String key, boolean defaultValue) {
  75. String value = env.getProperty(key);
  76. if (StringUtils.isBlank(value)) {
  77. return defaultValue;
  78. }
  79. return new Boolean(value);
  80. }
  81. /**
  82. * 加载配置信息
  83. * @param fullFile
  84. * @return
  85. * @throws IOException
  86. */
  87. public static Properties loadPropertyFile(String fullFile) throws IOException {
  88. Properties p = new Properties();
  89. if(fullFile == "" || "".equals(fullFile)){
  90. log.info("属性文件为空!~");
  91. }else{
  92. //加载属性文件
  93. InputStream inStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fullFile);
  94. try {
  95. p.load(inStream);
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. throw e;
  99. }
  100. }
  101. return p;
  102. }
  103. }