SpringBoot--外部配置

常見的SpringBoot外部配置有常規屬性配置、類型安全的配置、日誌配置、Profile配置java

1、常規屬性配置spring

在spring中,注入properties中的配置值時,須要兩步:sql

  • 經過註解@PropertySource指明 properties文件的位置
  • 經過註解@Value注入配置值

而在springboot中,只要將配置項加載配置文件中,就能夠經過註解@Value注入數據庫

例如我在application.properties中增長以下配置:apache

demo:
  userName: zhangsan
  message: HelloWorld

而後在類中就能夠直接經過註解@Value注入並獲取到值了:安全

 @Value("${demo.userName}")
    private String userName;

 @Value("${demo.message}")
    private String message;

2、類型安全的配置springboot

上面的配置方式,在配置項不少的狀況下,若是每一個都用註解@Value注入就很繁瑣了,針對這種狀況,springboot提供了一種稱之爲基於安全類型的配置方式,經過註解@ConfigurationProperties將properties(或者yml)屬性和一個bean及其屬性關聯,從而實現類型安全的配置。下面舉一個例子說明,本次我使用yml配置文件。app

一、首先新建一個自定義的配置文件user.yml框架

user:
  userName: zhangsan
  age: 26
  sex: male

二、建立一個名爲UserSettings.java的bean,與配置項中的屬性進行關聯spring-boot

package com.hyc.settings;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 基於類型安全的配置:將屬性中的配置映射成一個bean
 * 註解@PropertySource指定自定義配置文件的路徑
 * 註解@ConfigurationProperties加載配置文件中的配置項,prefix指定配置的前綴
 */ @Component
@PropertySource(value = "classpath:user.yml") @ConfigurationProperties(prefix = "user") public class UserSettings {
    private String userName;

    private int age;

    private String sex;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

上面的bean中,有三個註解,分別表明着:

  • @Component註解使這個類可以被掃描到;
  • @PropertySource註解中的value屬性定義對應的配置文件的路徑,若是是在application.yml(或application.properties)中,則不須要此註解;
  • @ConfigurationProperties註解將加載指定配置文件中的配置項,並經過屬性prefix指定配置的前綴,本例中是user

須要注意的是,這種方式須要增長下面的依賴:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
</dependency>

三、注入配置

直接在須要使用配置項值的類中,經過註解@Autowired注入bean,並經過調用它的get方法來獲取:

/**
     * 將配置項映射類自動注入,就能調用它的get方法獲取配置值了
     */
    @Autowired
    private UserSettings user;


    @RequestMapping("/")
    String index() {

        return "name: " + user.getUserName() + " age:" + user.getAge() + " sex:" + user.getSex();
    }

明顯這種方式看上去更加整潔清晰。

3、日誌配置

SpringBoot支持Java Util Logging、 Log4J、SLF4J和Logback多種日誌框架,可是默認是logback,這個能夠在日誌依賴配置

spring-boot-starter-logging-2.1.0.RELEASE.pom中找到,配置以下:

  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-logging</artifactId>
  <version>2.1.0.RELEASE</version>
  <name>Spring Boot Logging Starter</name>
  <description>Starter for logging using Logback. Default logging starter</description>
  <url>https://projects.spring.io/spring-boot/#/spring-boot-parent/spring-boot-starters/spring-boot-starter-logging</url>

上面紅色部分描述了springboot默認使用的是LogBack,可是在這個pom文件中,已經加入了其餘日誌的依賴,以下:

 <dependencies>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-to-slf4j</artifactId>
      <version>2.11.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>1.7.25</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

因此咱們使用時不須要額外增長相關日誌框架的依賴了!!!

  • 日誌級別及優先級爲trace<debug<info<warn<error;
  • 默認是info級別,就是會輸出優先級大於等於info的日誌;
  • 日誌默認輸出到控制檯,能夠設置輸出到文件,並配置文件路徑;

下面以上述三點爲例,在application.yml中進行配置:

1 logging:
2   file: ./log/demo.log
3   level:
4     com.hyc.*: trace

其中:

  • file用來配置日誌路徑及文件名;
  • level用來配置日誌級別,須要注意的是level須要以map的形式配置,不能直接在level後配置日誌級別,本例中的配置意義是com.hyc下全部包中的日誌級別都是trace,這樣就能夠給不一樣的包配置不一樣的日誌級別了;

下面來寫一個測試類,測試日誌的輸出:

@RestController
@SpringBootApplication
public class DemoApplication {

    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("/log")
    public void logging() {
        logger.trace("trace logger");
        logger.debug("debug logger");
        logger.info("info logger");
        logger.warn("warn logger");
        logger.error("error logger");
    }

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(DemoApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
}

運行,查看控制檯和日誌文件:

1️⃣控制檯

2018-11-27 17:35:33.127 TRACE 7038 --- [nio-8088-exec-2] ication$$EnhancerBySpringCGLIB$$43201a05 : trace logger
2018-11-27 17:35:33.128 DEBUG 7038 --- [nio-8088-exec-2] ication$$EnhancerBySpringCGLIB$$43201a05 : debug logger
2018-11-27 17:35:33.128  INFO 7038 --- [nio-8088-exec-2] ication$$EnhancerBySpringCGLIB$$43201a05 : info logger
2018-11-27 17:35:33.128  WARN 7038 --- [nio-8088-exec-2] ication$$EnhancerBySpringCGLIB$$43201a05 : warn logger
2018-11-27 17:35:33.128 ERROR 7038 --- [nio-8088-exec-2] ication$$EnhancerBySpringCGLIB$$43201a05 : error logger

2️⃣日誌文件

2018-11-27 17:35:32.788 TRACE 7038 --- [http-nio-8088-exec-1] ication$$EnhancerBySpringCGLIB$$43201a05 : trace logger
2018-11-27 17:35:32.789 DEBUG 7038 --- [http-nio-8088-exec-1] ication$$EnhancerBySpringCGLIB$$43201a05 : debug logger
2018-11-27 17:35:32.789  INFO 7038 --- [http-nio-8088-exec-1] ication$$EnhancerBySpringCGLIB$$43201a05 : info logger
2018-11-27 17:35:32.789  WARN 7038 --- [http-nio-8088-exec-1] ication$$EnhancerBySpringCGLIB$$43201a05 : warn logger
2018-11-27 17:35:32.789 ERROR 7038 --- [http-nio-8088-exec-1] ication$$EnhancerBySpringCGLIB$$43201a05 : error logger

由於配置的日誌級別是trace,因此會輸出trace及其以上級別的日誌;

除上述配置以外,還有其餘的一些配置,能夠參考下面默認配置項進行配置:

logging.config= # Location of the logging configuration file. For instance, `classpath:logback.xml` for Logback.
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory.
logging.file.max-history=0 # Maximum of archive log files to keep. Only supported with the default logback setup.
logging.file.max-size=10MB # Maximum log file size. Only supported with the default logback setup.
logging.level.*= # Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`.
logging.path= # Location of the log file. For instance, `/var/log`.
logging.pattern.console= # Appender pattern for output to the console. Supported only with the default Logback setup.
logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS # Appender pattern for log date format. Supported only with the default Logback setup.
logging.pattern.file= # Appender pattern for output to a file. Supported only with the default Logback setup.
logging.pattern.level=%5p # Appender pattern for log level. Supported only with the default Logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.

4、Profile配置

profile用來提供不一樣的環境配置,如開發環境、生產環境和測試環境中,須要使用不一樣的端口,數據庫等信息時,可使用profile來完成,基本用法分如下幾步:

  • 針對不一樣的環境建立不一樣的配置文件application-{profile}.yml(或application-{profile.properties})
  • 在全局配置application.yml中經過spring.profiles.active={profile}來指定環境

下面針對開發、測試、生產環境配置不一樣的端口和數據庫,來完成一次多環境的配置:

第一步:建立不一樣環境的配置文件

1️⃣開發環境application-dev.yml

server:
  port: 8088
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5433/dev?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: dev
    password: dev

2️⃣測試環境application.test.yml

server:
  port: 8088
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://10.192.22.5:5433/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: test
    password: test

3️⃣生產環境application-prod.yml

server:
  port: 88
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://10.192.22.3:5433/prod?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: prod
    password: prod

第二步:在全局配置application.yml中指定開發環境

server:
  port: 8088
  servlet:
    context-path: /
spring:
  profiles:
    active: dev

目錄以下:

注意:active後面的就是application-{profile}.yml中的profile的值!!!

能夠經過日誌查看是否配置成功:

 

因此,在springboot中能夠經過profile來配置多數據源!!

以上就是經常使用的配置。

相關文章
相關標籤/搜索