Spring Boot使用xxx.properties配置文件

  • 指定profile/xxx.properties配置文件

    • 在main函数上指定
    @PropertySource(value= {"classpath:redis.properties","classpath:database.properties"}
    			    , name="ss"
        			    , encoding="utf-8"
    			    ,ignoreResourceNotFound=true)
    
    • 运行时选择

      • 从Spring Boot项目根目录启动时指定:java org.springframework.boot.loader.JarLauncher —spring.profiles.active=xxx
      • 启动jar包时指定:java -Dspring.profiles.active=xxx -jar yyy.jar
    • 默认的profile/properties文件位置及命名规则

      • 在maven的pom.xml中指定
        • dev<profiles.active>dev</profiles.active>true
      • 启动maven项目时指定:man spring-boot:run -Drun.profiles=test
      • 在默认的application.properties中指定:spring.profiles.active=xxx
    • 命名方式

      • 默认profile配置文件:application.properties
      • application-{env}.properties
      • 当然也可以自己随便起名字,代码里自己去读properties文件
      Properties prop = new Properties();
      inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFileName)
      if(inputStream != null) {
          prop.load(inputStream);
      }
      
  • properties文件中的规则

    • 不能有同名的key,会报错
  • 使用/注入properties中的值

    • 如果环境变量中有相同的值,会覆盖properties文件中的默认值
    • cloudfoundry上,环境变量对应到properties文件中的key时,会把名字中的下划线”_”替换成点”.”
  • 如何加载多个properties文件

  • 常用固定配置

    • 日志
      • LOGGING_LEVEL_ROOT:DEBUG:日志输出等级
    • jvm
      • JAVA_OPTS
        • -Xss768K:每个线程的stack大小
        • -Xmx160M:Java heap的最大值,使用的最大内存
        • -Xms160M:初始heap大小,使用的最小内存,CPU性能高时此值应设的大一些
      • JBP_CONFIG_OPEN_JDK_JRE
        • {memory_calculator={stack_threads=100}}
  • 其他

    • 在Eclipse中,如果引入了相关的包,那么properties文件中在输入key时,会有自动感应和补全
原文地址:https://www.cnblogs.com/wyp1988/p/14357650.html