static静态方法使用yml配置文件的值

本是古典 何须时尚 2022-12-01 15:54 368阅读 0赞

static静态方法使用yml配置文件的值

  1. package com.longfor.falcon.modules.sys.utils;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Component;
  4. import javax.annotation.PostConstruct;
  5. /**
  6. * @Date 2020/8/28——10:22
  7. * @ClassName ReadYmlStaticParUtil
  8. * @Description: static静态方法使用yml配置文件的值
  9. * @Author hph
  10. **/
  11. @Component
  12. public class ReadYmlStaticParUtil {
  13. /*
  14. * @date 2020/8/28 ——10:28
  15. * @author hph
  16. * 注意事项:
  17. * 首选要在util里建一个static的变量,然后使用@Value获取yml配置文件的值。
  18. * 最后关键就是使用 @PostConstruct 熟悉将yml中配置的值赋给本地的变量,
  19. * 这样后面的静态方法就能使用了。
  20. * 被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会
  21. * 被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
  22. * PreDestroy()方法在destroy()方法执行执行之后执行。
  23. * 注意util类使用了 @Component 属性注解了说明是需要在启动类 Application
  24. * 启动的时候加载的,所以我们本地写一个方法调用 util 的时候是获取不到 name的。
  25. * @param
  26. * @return
  27. */
  28. //定义一个yml配置文件里的静态变量
  29. private static String userNames;
  30. //通过value获取yml配置文件参数
  31. @Value("${falcon.external.whiteList.userName}")
  32. private String userName;
  33. //利用@PostConstruct将yml中配置的值赋给本地的变量
  34. @PostConstruct
  35. public void getUserName(){
  36. userNames = this.userName;
  37. }
  38. public static String getName(){
  39. //输出打印控制台
  40. System.out.println(userNames);
  41. return userNames;
  42. }
  43. }

发表评论

表情:
评论列表 (有 0 条评论,368人围观)

还没有评论,来说两句吧...

相关阅读