Spring Boot 配置文件和命令行配置


Spring Boot 屬於約定大於配置,就是說 Spring Boot 推薦不做配置,很多都是默認配置,但如果想要配置系統,使得軟件符合業務定義,Spring Boot 可以通過多種方式進行配置。

Spring Boot 配置文件默認在 src/main/resouces/application.properties ,配置文件可以是 .properties 也可以是 .yml 后綴。兩者除了展示形式,沒有區別。

配置文件的三種方式

  1. bootstrap 開頭 .properties 后綴 或 .yml 后綴,通常用於 Spring Cloud 應用
  2. application 開頭 .properties 后綴 或 .yml 后綴,每個 Spring Boot 應用默認
  3. 通過 @Configuration 注解的代碼類配置
  4. 通過 cmd 命令行配置

1 bootstrap

1.1 bootstrap 應用場景

因為本系列是 Spring Boot 教程實例,沒有設計到 Spring Cloud ,而 Bootstrap 實際應用場景是在 Spring Cloud,本章也不具體討論。

1.2 bootstrap 與 application

bootstrap.yml(bootstrap.properties)用來程序引導時執行,應用於更加早期配置信息讀取,如可以使用來配置application.yml中使用到參數等。

application.yml(application.properties) 應用程序特有配置信息,可以用來配置后續各個模塊中需使用的公共參數等。

bootstrap.yml 先於 application.yml 加載

為什么要有 bootstrap 配置

2 application

application.yml(application.properties) 是針對獨立 Spring Boot 的應用配置文件,跟 .NET 的 web.confg(app.confg) 文件功能一樣。

2.1 application 常用配配置

2.1.1 端口配置

properties 格式

#指定springboot內嵌容器啟動的端口,默認使用tomcat容器時在8080端口    
server.port=8081

yml 格式

#指定springboot內嵌容器啟動的端口,默認使用tomcat容器時在8080端口    
server
    port: 8081

2.1.2 thymeleaf組件配置

properties 格式

#是否開啟thymeleaf緩存
spring.thymeleaf.cache=false
#thymeleaf路徑
spring.thymeleaf.prefix=classpath:/templates/ 
#后綴
spring.thymeleaf.suffix=.html
#編碼
spring.thymeleaf.encoding=UTF-8
#文本類型
spring.thymeleaf.content-type=text/html
#展示形式
spring.thymeleaf.mode=HTML5

yml 格式

#thymelea模板配置
spring:
  thymeleaf:
    #緩存
    cache: false
    #thymeleaf 所在路徑
    prefix: classpath:/templates/
    #thymeleaf 后綴
    suffix: .html
    #thymeleaf 采用的標准
    mode: HTML5
    #thymeleaf 編碼格式
    encoding: UTF-8

2.1.3 數據庫連接配置

properties 格式

#描述數據源 #編碼、時區等格式
spring.datasource.url=jdbc:mysql://localhost:3306/tanglong?useUnicode=true&
characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia
#數據源用戶名
spring.datasource.username=root
#數據源密碼
spring.datasource.password=0000
#數據源驅動包名
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
#數據源類型
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource

2.1.4 數據持久化

#是否打印sql語句
spring.jpa.show-sql= true
#mybatis配置文件路徑
mybatis.config-location=classpath:MyBatis.xml
#指定 mybatis 本地路徑,例如在 mybatis/mappings 下所有的 xml 后綴的文件
mybatis.mapper-locaitons=classpath:mybatis/mappings/*.xml
#打印myBatis的sql語句 com.demo.mapper  為包名
logging.level.com.demo.mapper=debug
#別名實體包,多個逗號隔開
mybatis.type-aliases-package=com.user.bean

2.1.5 多種開發環境

多環境配置請參見 Spring Boot 多環境如何配置

#開發/測試/生產環境分別對應dev/test/prod,可以自由定義,當前配置為開發環境
spring.profiles.active=dev

#不同環境中的配置信息可以寫在其他文件中
application-test.properties 或者 application-prod.properties

2.2 如何獲取 application 中的值

2.2.1 新建一個類標注 @ConfigurationProperties

  1. 新建一個 java 類
  2. 給類加 @ConfigurationProperties(prefix = "corn") 其中 prefix 表前綴,例如 corn.username=123,那么corn就是前綴
    假設 application.yml 代碼如下
corn:
  uploadPath: /Users/jiaojunkang/Documents/project_java/corn/src/corn-master/files/
  rootPath: /Users/jiaojunkang/Documents/project_java/fwrsoft/html/
  host: corn.icontag.cn
  componentAppId:
  componentSecret:
  componentToken:
  componentAesKey:
  baiduApikey:
  baiduSecretkey:
  baiduAppId:
  smsUrl:
  smsUid:
  smsPwd:
  pageSize: 10

那么對應的 java 配置類


@Component
@ConfigurationProperties(prefix = "corn")
public class CornConfig {
    //上傳路徑
    private String uploadPath;

    //靜態文件跟目錄
    private String rootPath;

    //HOST
    private String host;
    //微信開發平台appid
    private String componentAppId;
    private String componentSecret;
    private String componentToken;
    private String componentAesKey;

    private String baiduApikey;
    private String baiduSecretkey;

    private   String  smsUrl;

    private String pageSize;

    public String getPageSize() {
        return pageSize;
    }

    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }

    public String getSmsUrl() {
        return smsUrl;
    }

    public void setSmsUrl(String smsUrl) {
        this.smsUrl = smsUrl;
    }

    public String getSmsUid() {
        return smsUid;
    }

    public void setSmsUid(String smsUid) {
        this.smsUid = smsUid;
    }

    public String getSmsPwd() {
        return smsPwd;
    }

    public void setSmsPwd(String smsPwd) {
        this.smsPwd = smsPwd;
    }

    private   String  smsUid;

    private   String  smsPwd;


    public String getBaiduAppId() {
        return baiduAppId;
    }

    public void setBaiduAppId(String baiduAppId) {
        this.baiduAppId = baiduAppId;
    }

    private String baiduAppId;



    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String getRootPath() {
        return rootPath;
    }

    public void setRootPath(String rootPath) {
        this.rootPath = rootPath;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getComponentAppId() {
        return componentAppId;
    }

    public void setComponentAppId(String componentAppId) {
        this.componentAppId = componentAppId;
    }

    public String getComponentSecret() {
        return componentSecret;
    }

    public void setComponentSecret(String componentSecret) {
        this.componentSecret = componentSecret;
    }

    public String getComponentToken() {
        return componentToken;
    }

    public void setComponentToken(String componentToken) {
        this.componentToken = componentToken;
    }

    public String getComponentAesKey() {
        return componentAesKey;
    }

    public void setComponentAesKey(String componentAesKey) {
        this.componentAesKey = componentAesKey;
    }

    public String getBaiduApikey() {
        return baiduApikey;
    }

    public void setBaiduApikey(String baiduApikey) {
        this.baiduApikey = baiduApikey;
    }

    public String getBaiduSecretkey() {
        return baiduSecretkey;
    }

    public void setBaiduSecretkey(String baiduSecretkey) {
        this.baiduSecretkey = baiduSecretkey;
    }
}

2.2.2 在普通的類中使用 value 配置

給屬性增加 @Value 標簽,例如 使用 @Value("${spring.redis.host}") 標注 host 表示 Redis

@Value("${spring.redis.host}")
    private String host = "127.0.0.1";

    @Value("${spring.redis.port}")
    private int port = 6379;

    // 0 - never expire
    private int expire = 0;

    //timeout for jedis try to connect to redis server, not expire time! In milliseconds
    @Value("${spring.redis.timeout}")
    private int timeout = 0;

    @Value("${spring.redis.password}")
    private String password = "";

3 @Configuration

使用 @Configuration 也可以替代部分 application.yml 文件配置,但 @Configuration 可以更加靈活的實現配置的自定義,他們的區別或者在於 @Configuration 可以動態配置,缺點是一旦發布無法更改。

  1. @Configuration 通常用於 aplication的補充
  2. @Configuration 用在類上,@Bean 用在方法上

例如配置 QuartzConfigration 通常采用的配置


@Configuration
public class QuartzConfigration {
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/config/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    // 創建schedule
    @Bean(name = "scheduler")
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }
}

4 命令行配置

Spring Boot 在服務器部署可以使用下面命令,這時使用 -- 開頭引入 spring 中的 application 的值,即可在命令行配置 Spring Boot。

java -jar xxxx-0.0.1-SNAPSHOT.jar

我們可以通過在命令行增加配置的方式給 Spring Boot 添加配置,命令行配置優先於 application.yml 執行。

如下配置了一個端口,使用 --server.port=8088 配置 來實現命令行配置

java -jar xxxx-0.0.1-SNAPSHOT.jar --server.port=8088 --spring.profiles.active=dev


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM