自动配置 Azure SDK 客户端

Spring Boot 简化了 Spring Cloud Azure 开发体验。 Spring Cloud Azure 初学者是一组方便的依赖项描述符,可包含在应用程序中。 初学者处理对象实例化和配置逻辑,因此无需。 每个初学者都依赖于 spring-cloud-azure-starter 来提供关键配置位,例如 Azure 云环境和身份验证信息。 可以将这些配置为属性,例如 YAML 文件,如以下示例所示:

spring:
  cloud:
    azure:
      profile:
        tenant-id: <tenant>
        cloud-type: Azure
      credential:
        client-id: ${AZURE_CLIENT_ID}

注意

cloud 属性是可选的。

允许 tenant-id 的值包括:commonorganizationsconsumers或租户 ID。 有关这些值的详细信息,请参阅 使用错误的终结点(个人和组织帐户)错误AADSTS50020 - 租户中不存在来自标识提供者的用户帐户。 有关转换单租户应用的信息,请参阅 在 Microsoft Entra ID上将单租户应用转换为多租户。

这些属性是可选的,如果未指定,Spring Boot 将尝试自动查找它们。 有关 Spring Boot 如何查找这些属性的详细信息,请参阅文档。

依赖项设置

有两种方法可以使用 Spring Cloud Azure 初学者。 第一种方法是将 Azure SDK 与 spring-cloud-azure-starter 依赖项配合使用,如以下示例所示:

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-cosmos</artifactId>
</dependency>
<dependency>
    <groupId>com.azure.spring</groupId>
    <artifactId>spring-cloud-azure-starter</artifactId>
</dependency>

第二种方法是避免添加 Azure SDK 依赖项,而是直接为每个服务包含 Spring Cloud Azure Starter。 例如,使用 Azure Cosmos DB,可以添加以下依赖项:

<dependency>
    <groupId>com.azure.spring</groupId>
    <artifactId>spring-cloud-azure-starter-cosmos</artifactId>
</dependency>

提示

有关受支持的初学者列表,请参阅 Spring Cloud Azure 开发人员指南初学者依赖项 部分。

配置

注意

如果使用安全主体通过 Microsoft Entra ID 进行身份验证和授权来访问 Azure 资源,请确保安全主体已获得足够的权限来访问 Azure 资源。 有关详细信息,请参阅 使用 Microsoft Entra ID授权访问。

每个 Azure 服务的配置属性都位于前缀 spring.cloud.azure.<azure-service>下。

提示

有关所有 Spring Cloud Azure 配置属性的列表,请参阅 Spring Cloud Azure 配置属性

基本用法

将以下属性添加到 application.yaml 文件将为你自动配置 Azure Cosmos DB 客户端。

spring:
  cloud:
    azure:
      cosmos:
        database: ${AZURE_COSMOS_DATABASE_NAME}
        endpoint: ${AZURE_COSMOS_ENDPOINT}
        consistency-level: eventual
        connection-mode: direct

然后,上下文中提供了 CosmosClientCosmosAsyncClient,并且可以自动连接,如以下示例所示:

class Demo {
@Autowired
private CosmosClient cosmosClient;

    @Override
    public void run() {
        User item = User.randomUser();
        CosmosContainer container = cosmosClient.getDatabase(databaseName).getContainer(containerName);
        container.createItem(item);
    }
}

样品

请参阅 GitHub 上的 azure-spring-boot-samples