最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

12個(gè)SpringBoot配置文件的實(shí)用技巧分享

 更新時(shí)間:2025年05月12日 08:17:30   作者:風(fēng)象南  
配置文件是SpringBoot應(yīng)用的核心組成部分,它決定了應(yīng)用的行為、連接參數(shù)以及功能特性,本文為大家整理了12個(gè)SpringBoot配置文件的實(shí)用技巧,有需要的可以了解下

配置文件是SpringBoot應(yīng)用的核心組成部分,它決定了應(yīng)用的行為、連接參數(shù)以及功能特性。

合理利用SpringBoot的配置機(jī)制,不僅可以提高開發(fā)效率,還能增強(qiáng)應(yīng)用的靈活性和可維護(hù)性。

1. 多環(huán)境配置(Profiles)

SpringBoot支持通過(guò)profiles實(shí)現(xiàn)多環(huán)境配置,便于在開發(fā)、測(cè)試和生產(chǎn)環(huán)境之間無(wú)縫切換。

基本用法

創(chuàng)建特定環(huán)境的配置文件:

• application-dev.yml(開發(fā)環(huán)境)

• application-test.yml(測(cè)試環(huán)境)

• application-prod.yml(生產(chǎn)環(huán)境)

在主配置文件application.yml中激活特定環(huán)境:

spring:
  profiles:
    active: dev

高級(jí)配置

使用分組功能(Spring Boot 2.4+)來(lái)簡(jiǎn)化環(huán)境配置:

spring:
  profiles:
    group:
      dev: local-db, local-cache, dev-api
      prod: cloud-db, redis-cache, prod-api

命令行激活

無(wú)需修改配置文件,直接在啟動(dòng)時(shí)指定環(huán)境:

java -jar app.jar --spring.profiles.active=prod

2. 配置屬性的優(yōu)先級(jí)

了解SpringBoot配置的優(yōu)先級(jí)順序,有助于解決配置沖突。

常見配置源優(yōu)先級(jí)(從高到低):

1. 命令行參數(shù)

2. Java系統(tǒng)屬性(System.getProperties())

3. 操作系統(tǒng)環(huán)境變量

4. 特定profile的配置文件

5. 應(yīng)用程序外部的application.properties/yml

6. 應(yīng)用程序內(nèi)部的application.properties/yml

應(yīng)用示例

對(duì)于數(shù)據(jù)庫(kù)URL配置,可以在不同級(jí)別設(shè)置:

# application.yml (優(yōu)先級(jí)低)
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/default_db
# 命令行參數(shù) (優(yōu)先級(jí)高)
java -jar app.jar --spring.datasource.url=jdbc:mysql://prod-server:3306/prod_db

最終生效的是命令行參數(shù)中的URL。

3. 松散綁定(Relaxed Binding)

SpringBoot支持多種屬性命名風(fēng)格,自動(dòng)進(jìn)行松散綁定,提高配置的靈活性。

支持的命名風(fēng)格

對(duì)于Java屬性serverPort

• kebab-case:server-port(推薦用于.properties和.yml文件)

• 駝峰式:serverPort

• 下劃線:server_port(推薦用于環(huán)境變量)

• 全大寫下劃線:SERVER_PORT(環(huán)境變量的標(biāo)準(zhǔn)格式)

綁定示例

配置文件:

my-app:
  connection-timeout: 5000
  read-timeout: 10000

Java代碼:

@ConfigurationProperties(prefix = "my-app")
public class AppProperties {
    private int connectionTimeout;
    private int readTimeout;
    
    // getters and setters
}

SpringBoot會(huì)自動(dòng)將connection-timeout綁定到connectionTimeout屬性。

4. 配置隨機(jī)值

在開發(fā)和測(cè)試環(huán)境中,經(jīng)常需要生成隨機(jī)值,SpringBoot提供了內(nèi)置支持。

常用隨機(jī)屬性

app:
  # 隨機(jī)整數(shù)
  random-int: ${random.int}
  # 范圍內(nèi)的隨機(jī)整數(shù)
  random-int-range: ${random.int[1000,2000]}
  # 隨機(jī)長(zhǎng)整數(shù)
  random-long: ${random.long}
  # 隨機(jī)字符串
  random-string: ${random.uuid}
  # 隨機(jī)字節(jié)
  secret-key: ${random.bytes[16]}

應(yīng)用場(chǎng)景

服務(wù)器端口隨機(jī)分配,避免開發(fā)環(huán)境端口沖突:

server:
  port: ${random.int[8000,9000]}

測(cè)試環(huán)境使用隨機(jī)密鑰:

app:
  security:
    secret-key: ${random.uuid}

5. 類型安全的配置屬性(@ConfigurationProperties)

使用@ConfigurationProperties綁定結(jié)構(gòu)化配置,提供類型安全和代碼自動(dòng)完成。

基本用法

配置類:

@Component
@ConfigurationProperties(prefix = "mail")
@Validated
public class MailProperties {
    
    @NotEmpty
    private String host;
    
    @Min(1025)
    @Max(65536)
    private int port = 25;
    
    @Email
    private String from;
    
    private boolean enabled;
    
    // getters and setters
}

配置文件:

mail:
  host: smtp.example.com
  port: 587
  from: noreply@example.com
  enabled: true

集合與復(fù)雜類型

mail:
  recipients:
    - admin@example.com
    - support@example.com
  connection:
    timeout: 5000
    retry: 3
  additional-headers:
    X-Priority: 1
    X-Mailer: MyApp
@ConfigurationProperties(prefix = "mail")
public class MailProperties {
    private List<String> recipients = new ArrayList<>();
    private Connection connection = new Connection();
    private Map<String, String> additionalHeaders = new HashMap<>();
    
    // getters and setters
    
    public static class Connection {
        private int timeout;
        private int retry;
        
        // getters and setters
    }
}

6. 導(dǎo)入其他配置文件

在大型項(xiàng)目中,將配置拆分為多個(gè)文件可以提高可維護(hù)性。

使用@PropertySource

@Configuration
@PropertySource("classpath:db.properties")
@PropertySource("classpath:cache.properties")
public class AppConfig {
    // ...
}

使用spring.config.import

在Spring Boot 2.4+中,可以在主配置文件中導(dǎo)入其他配置:

spring:
  config:
    import:
      - classpath:db.yml
      - optional:file:./config/local.yml
      - configserver:http://config-server:8888/

注意optional:前綴表示文件不存在也不會(huì)報(bào)錯(cuò)。

7. 敏感配置的加密與保護(hù)

在生產(chǎn)環(huán)境中,保護(hù)敏感配置如密碼和API密鑰至關(guān)重要。

使用Jasypt加密

1. 添加Jasypt依賴:

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>

2. 加密配置值:

# 加密后的配置
spring.datasource.password=ENC(G8Sn36MAJOWJwEgAMZM3Cw0QC9rEEVyn)

3. 提供解密密鑰:

java -jar app.jar --jasypt.encryptor.password=mySecretKey

使用環(huán)境變量存儲(chǔ)敏感信息

spring:
  datasource:
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}

8. 配置屬性校驗(yàn)

對(duì)配置屬性進(jìn)行校驗(yàn),避免不合法的配置導(dǎo)致運(yùn)行時(shí)錯(cuò)誤。

使用JSR-303校驗(yàn)

@ConfigurationProperties(prefix = "app.connection")
@Validated
public class ConnectionProperties {
    
    @NotNull
    @Min(1000)
    @Max(10000)
    private Integer timeout;
    
    @Pattern(regexp = "^(http|https)://.*$")
    private String serviceUrl;
    
    @Email
    private String supportEmail;
    
    // getters and setters
}

自定義校驗(yàn)

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IpAddressValidator.class)
public @interface IpAddress {
    String message() default "Invalid IP address";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class IpAddressValidator implements ConstraintValidator<IpAddress, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        String regex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return value.matches(regex);
    }
}

@ConfigurationProperties(prefix = "app.server")
@Validated
public class ServerProperties {
    @IpAddress
    private String ipAddress;
    // ...
}

9. 配置中使用占位符

在配置文件中使用占位符引用其他配置項(xiàng),提高靈活性和減少重復(fù)。

基本用法

app:
  name: MyApp
  api:
    base-url: http://api.example.com
    version: v1
    full-url: ${app.api.base-url}/${app.api.version}
  security:
    timeout: 3600
    timeout-millis: ${app.security.timeout}000

默認(rèn)值

提供默認(rèn)值以防配置缺失:

app:
  cache-dir: ${CACHE_DIR:/tmp/cache}
  max-threads: ${MAX_THREADS:10}

系統(tǒng)屬性和環(huán)境變量引用

server:
  port: ${PORT:8080}
  address: ${SERVER_ADDRESS:0.0.0.0}
  
logging:
  path: ${LOG_PATH:${user.home}/logs}

10. 配置條件化加載

使用Spring的條件注解根據(jù)條件加載配置,提高靈活性。

使用@Profile

@Configuration
@Profile("dev")
public class DevDatabaseConfig {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .build();
    }
}

@Configuration
@Profile("prod")
public class ProdDatabaseConfig {
    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://prod-db:3306/app");
        // 其他配置...
        return dataSource;
    }
}

使用@Conditional

@Configuration
@ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true")
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }
}

@Configuration
@ConditionalOnMissingBean(CacheManager.class)
public class NoCacheConfig {
    // 備用配置
}

基于類路徑條件

@Configuration
@ConditionalOnClass(name = "org.springframework.data.redis.core.RedisTemplate")
public class RedisConfig {
    // Redis相關(guān)配置
}

11. 列表和Map配置技巧

在配置文件中有效地表示復(fù)雜數(shù)據(jù)結(jié)構(gòu)。

YAML中的列表

app:
  # 簡(jiǎn)單列表
  servers:
    - server1.example.com
    - server2.example.com
    - server3.example.com
  
  # 對(duì)象列表
  endpoints:
    - name: users
      url: /api/users
      method: GET
    - name: orders
      url: /api/orders
      method: POST

在Java中綁定:

@ConfigurationProperties(prefix = "app")
public class AppConfig {
    private List<String> servers = new ArrayList<>();
    private List<Endpoint> endpoints = new ArrayList<>();
    
    // getters and setters
    
    public static class Endpoint {
        private String name;
        private String url;
        private String method;
        
        // getters and setters
    }
}

Map配置

app:
  # 簡(jiǎn)單映射
  feature-flags:
    enableNewUI: true
    enableAnalytics: false
    enableNotifications: true

  # 復(fù)雜映射
  datasources:
    main:
      url: jdbc:mysql://main-db:3306/app
      username: mainuser
      maxPoolSize: 20
    report:
      url: jdbc:mysql://report-db:3306/reports
      username: reportuser
      maxPoolSize: 5

在Java中綁定:

@ConfigurationProperties(prefix = "app")
public class AppConfig {
    private Map<String, Boolean> featureFlags = new HashMap<>();
    private Map<String, DataSourceProperties> datasources = new HashMap<>();
    
    // getters and setters
    
    public static class DataSourceProperties {
        private String url;
        private String username;
        private int maxPoolSize;
        
        // getters and setters
    }
}

12. 使用Spring Boot配置元數(shù)據(jù)

創(chuàng)建配置元數(shù)據(jù),提供IDE自動(dòng)完成和文檔。

添加元數(shù)據(jù)依賴

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

配置類添加文檔

@ConfigurationProperties(prefix = "acme")
public class AcmeProperties {

    /**
     * 是否啟用ACME服務(wù)。
     */
    private boolean enabled = false;

    /**
     * 服務(wù)的遠(yuǎn)程地址。
     */
    @NotEmpty
    private String remoteAddress;

    /**
     * 會(huì)話超時(shí)時(shí)間,單位為秒。
     * 最小值為1分鐘,最大值為1小時(shí)。
     */
    @Min(60)
    @Max(3600)
    private int sessionTimeout = 600;

    // getters和setters
}

自定義元數(shù)據(jù)

創(chuàng)建META-INF/additional-spring-configuration-metadata.json文件:

{
  "properties": [
    {
      "name": "app.security.api-key",
      "type": "java.lang.String",
      "description": "API安全密鑰,用于外部服務(wù)認(rèn)證。",
      "sourceType": "com.example.AppSecurityProperties"
    },
    {
      "name": "app.rate-limit.enabled",
      "type": "java.lang.Boolean",
      "description": "是否啟用API速率限制。",
      "defaultValue": true,
      "deprecation": {
        "level": "warning",
        "replacement": "app.security.rate-limit.enabled",
        "reason": "API速率限制配置已移動(dòng)到security命名空間。"
      }
    }
  ],
  "hints": [
    {
      "name": "app.log-level",
      "values": [
        {
          "value": "debug",
          "description": "調(diào)試日志級(jí)別。"
        },
        {
          "value": "info",
          "description": "信息日志級(jí)別。"
        },
        {
          "value": "warn",
          "description": "警告日志級(jí)別。"
        },
        {
          "value": "error",
          "description": "錯(cuò)誤日志級(jí)別。"
        }
      ]
    }
  ]
}

總結(jié)

在實(shí)際開發(fā)中,我們應(yīng)根據(jù)項(xiàng)目規(guī)模和復(fù)雜度選擇合適的配置策略。

通過(guò)合理應(yīng)用這些技巧,我們可以構(gòu)建更加靈活、安全且易于維護(hù)的SpringBoot應(yīng)用,為業(yè)務(wù)需求的快速變化提供堅(jiān)實(shí)的技術(shù)支持。

到此這篇關(guān)于12個(gè)SpringBoot配置文件的實(shí)用技巧分享的文章就介紹到這了,更多相關(guān)SpringBoot配置文件實(shí)用技巧內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java冒泡排序和選擇排序詳解

    java冒泡排序和選擇排序詳解

    這篇文章主要介紹了java數(shù)組算法例題代碼詳解(冒泡排序,選擇排序),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-07-07
  • SpringBoot中@Scheduled()注解以及cron表達(dá)式詳解

    SpringBoot中@Scheduled()注解以及cron表達(dá)式詳解

    這篇文章主要介紹了SpringBoot中@Scheduled()注解以及cron表達(dá)式詳解,@Scheduled注解是Spring Boot提供的用于定時(shí)任務(wù)控制的注解,主要用于控制任務(wù)在某個(gè)指定時(shí)間執(zhí)行,或者每隔一段時(shí)間執(zhí)行,需要的朋友可以參考下
    2023-08-08
  • java虛擬機(jī)鉤子關(guān)閉函數(shù)addShutdownHook的操作

    java虛擬機(jī)鉤子關(guān)閉函數(shù)addShutdownHook的操作

    這篇文章主要介紹了java虛擬機(jī)鉤子關(guān)閉函數(shù)addShutdownHook的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • kkFileView啟動(dòng)報(bào)錯(cuò):報(bào)錯(cuò)2003端口占用的問(wèn)題及解決

    kkFileView啟動(dòng)報(bào)錯(cuò):報(bào)錯(cuò)2003端口占用的問(wèn)題及解決

    kkFileView啟動(dòng)報(bào)錯(cuò)因office組件2003端口未關(guān)閉,解決:查殺占用端口的進(jìn)程,終止Java進(jìn)程,使用shutdown.sh腳本優(yōu)雅關(guān)閉,再通過(guò)startup.sh或jar命令重啟
    2025-07-07
  • Java 讀取文件方法大全

    Java 讀取文件方法大全

    這篇文章主要介紹了Java 讀取文件方法大全,需要的朋友可以參考下
    2014-11-11
  • java實(shí)現(xiàn)輸出文件夾下某個(gè)格式的所有文件實(shí)例代碼

    java實(shí)現(xiàn)輸出文件夾下某個(gè)格式的所有文件實(shí)例代碼

    這篇文章主要介紹了java實(shí)現(xiàn)輸出文件夾下某個(gè)格式的所有文件,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-06-06
  • Java String對(duì)象使用方法詳解

    Java String對(duì)象使用方法詳解

    這篇文章主要介紹了Java String對(duì)象使用方法詳解的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • Spring循環(huán)依賴產(chǎn)生與解決

    Spring循環(huán)依賴產(chǎn)生與解決

    Spring的解決循環(huán)依賴是有前置條件的,要解決循環(huán)依賴我們首先要了解Spring Bean對(duì)象的創(chuàng)建過(guò)程和依賴注入的方式。依賴注入方式,我之前的博客有所分享,大家可以在看本篇文章之前進(jìn)行一下小小的回顧
    2022-12-12
  • Java 中 synchronized的用法詳解(四種用法)

    Java 中 synchronized的用法詳解(四種用法)

    Java語(yǔ)言的關(guān)鍵字,當(dāng)它用來(lái)修飾一個(gè)方法或者一個(gè)代碼塊的時(shí)候,能夠保證在同一時(shí)刻最多只有一個(gè)線程執(zhí)行該段代碼。本文給大家介紹java中 synchronized的用法,對(duì)本文感興趣的朋友一起看看吧
    2015-11-11
  • Java Unsafe 類的講解

    Java Unsafe 類的講解

    這篇文章主要給大家分享了 Java Unsafe 類的講解,文章圍繞Unsafe 類的相關(guān)資料展開詳細(xì)內(nèi)容,具有一定的參考價(jià)值需要的朋友可以參考一下
    2021-11-11

最新評(píng)論

周宁县| 墨竹工卡县| 扎赉特旗| 巴南区| 皋兰县| 牡丹江市| 阿拉善盟| 永胜县| 宽甸| 特克斯县| 华坪县| 浠水县| 治多县| 嵩明县| 贺兰县| 临西县| 浮梁县| 图们市| 溆浦县| 亚东县| 康定县| 铜川市| 巴中市| 陇西县| 社会| 南投县| 泊头市| 新民市| 东至县| 丰宁| 吴忠市| 信丰县| 大厂| 龙游县| 土默特右旗| 渑池县| 定州市| 子洲县| 洛隆县| 桐庐县| 罗定市|