知識庫 / Spring / Spring Boot RSS 訂閱

Spring Boot 屬性前綴必須為規範形式

Spring Boot
HongKong
5
11:34 AM · Dec 06 ,2025

1. 概述

本快速教程將深入探討 Spring Boot 中的錯誤原因。首先,我們將闡明此錯誤的主要原因。然後,我們將通過一個實際示例,講解如何重現和解決該問題。

2. 問題陳述

首先,讓我們理解錯誤消息的含義。“Canonical 名稱應採用 kebab-case 格式” 簡單來説,告訴我們 Canonical 名稱(Canonical 名稱是指唯一標識屬性的屬性名稱)應採用 kebab-case 格式。

為了確保一致性,前綴 參數中 @ConfigurationProperties 註解中使用的命名約定應遵循 kebab 格式。

例如:

@ConfigurationProperties(prefix = "my-example")

在上述代碼片段中,前綴 my-example 應遵循 kebab 命名約定。

3. Maven 依賴

由於這是一個基於 Maven 的項目,我們將在 pom.xml 中添加必要的依賴:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter</artifactId> 
    <version>3.0.5</version>
</dependency>

為了重現該問題,spring-boot-starter 是唯一需要的依賴項。

4. 重新創建錯誤

This section describes how to reproduce the error you are experiencing. Reproducing the error is a crucial step in debugging and understanding the root cause. It allows you to verify your hypothesis and isolate the specific conditions that trigger the issue.

Steps to Reproduce:

  1. Start with a clean environment. Ensure your system is free of any conflicting software or configurations.
  2. Follow the documented steps. Carefully execute the steps outlined in the Troubleshooting Guide.
  3. Monitor the system. Pay close attention to any error messages, logs, or performance metrics that may provide clues.
  4. Isolate the variables. Change one variable at a time to see if it affects the error. This can help you identify the specific setting or configuration that is causing the problem.

Example:

def calculate_sum(a, b):
  """
  This function calculates the sum of two numbers.
  """
  return a + b

# Example usage
result = calculate_sum(5, 3)
print(result)

4.1. 應用配置

如果您不熟悉配置屬性,可以通過探索 Spring Boot 中的 ConfigurationProperties 指南 來獲得更深入的瞭解。

讓我們註冊所需的組件:
@Configuration
@ConfigurationProperties(prefix = "customProperties")
public class MainConfiguration {
    String name;
 
    // getters and setters
}

然後,我們需要向 application.properties文件中添加一個自定義屬性:

custom-properties.name="Baeldung"

應用程序的配置文件位於 src/main/resources 下。

|   pom.xml
+---src
|   +---main
|   |   +---java
|   |   |   \---com
|   |   |       \---baeldung
|   |   |           ...
|   |   |           ...
|   |   \---resources
|   |           application.properties

現在,讓我們通過在項目根目錄下執行命令 mvn spring-boot:run 來運行我們的示例 Spring Boot 應用程序,並查看結果:

$ mvn spring-boot:run
...
...
***************************
APPLICATION FAILED TO START
***************************

Description:

Configuration property name 'customProperties' is not valid:

    Invalid characters: 'P'
    Bean: mainConfiguration
    Reason: Canonical names should be kebab-case ('-' separated), lowercase alpha-numeric characters and must start with a letter

Action:

Modify 'customProperties' so that it conforms to the canonical names requirements.

如上所示,我們得到一個錯誤消息:修改 ‘customProperties’ 以符合 Spring 的規範命名要求。 錯誤消息表明當前用於 customProperties 的命名約定不符合 Spring 的命名約定。換句話説,名稱 customProperties 需要更改以符合 Spring 中屬性命名的要求。

5. 修復錯誤

我們需要將屬性前綴從以下更改:

@ConfigurationProperties(prefix = "customProperties")

轉換為 kebab 命名規範前綴:

@ConfigurationProperties(prefix = "custom-properties")

在屬性中,我們可以保留任何樣式,並且能夠順利訪問它們。

6. 使用切片式命名(Kebab Casing)的優勢

使用切片式命名(Kebab Casing)訪問這些屬性的主要優勢在於,我們可以在以下任何一種格式中使用:

  • camelCaseLikeThis
  • PascalCaseLikeThis
  • snake_case_like_this
  • kebab-case-like-this

在 `properties 文件中,並使用切片式命名進行訪問。

@ConfigurationProperties(prefix = "custom-properties")

將能夠訪問以下所有屬性

customProperties.name="Baeldung"
CustomProperties.name="Baeldung"
custom_properties.name="Baeldung"
custom-properties.name="Baeldung"
<div>
  <h1>Introduction</h1>
  <p>This document provides an overview of the new API. It covers key concepts, usage examples, and troubleshooting tips.</p>

  <h2>Key Concepts</h2>
  <ul>
    <li><strong>Authentication:</strong>  The process of verifying the identity of a user or application.</li>
    <li><strong>Authorization:</strong>  Determining what resources a user or application is allowed to access.</li>
    <li><strong>API Endpoints:</strong>  Specific URLs that represent resources within the API.</li>
  </ul>

  <h2>Usage Examples</h2>
  <pre><code>
  // Example JavaScript code
  function fetchData(url) {
    // Make an HTTP request to the specified URL
    fetch(url)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }

  fetchData('https://api.example.com/users');
  </code></pre>

  <p>This example demonstrates how to use the API to retrieve user data.</p>

  <h2>Troubleshooting</h2>
  <h3>Common Errors</h3>
  <ul>
    <li><strong>400 Bad Request:</strong>  The request was malformed or missing required parameters.</li>
    <li><strong>401 Unauthorized:</strong>  The user is not authenticated.</li>
    <li><strong>404 Not Found:</strong>  The requested resource does not exist.</li>
  </ul>
</div>

7. 結論

在本教程中,我們瞭解到 Spring Boot 支持多種命名格式,包括駝峯命名法(camel case)、蛇形命名法(snake case)和燕麥麩命名法(kebab case)在屬性名稱中的使用,但它鼓勵我們以燕麥麩命名法訪問它們,從而降低因不一致的命名約定而導致錯誤或混淆的可能性。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.