You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于多环境配置文件配置Java Application Insights连接字符串?

从多环境配置文件中配置Application Insights连接字符串(新版本)

1. 在环境专属配置文件中添加连接字符串

在src/main/profile/dev/osoz-config.properties和src/main/profile/prod/osoz-config.properties中分别添加对应环境的连接字符串:

# dev环境
azure.application-insights.connection-string=DEV_ENV_CONNECTION_STRING

# prod环境
azure.application-insights.connection-string=PROD_ENV_CONNECTION_STRING

2. 引入正确的依赖

如果使用Spring Boot,推荐引入官方的starter依赖(适配最新版本的Application Insights SDK):

Maven

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>application-insights-spring-boot-starter</artifactId>
    <version>3.4.14</version> <!-- 使用最新稳定版本 -->
</dependency>

Gradle

implementation 'com.microsoft.azure:application-insights-spring-boot-starter:3.4.14'

3. 自动配置(推荐方案)

新版本的Application Insights Spring Starter会自动读取azure.application-insights.connection-string配置项,无需手动处理旧版的TelemetryConfiguration类。启动应用时,SDK会根据当前激活的环境配置,自动加载对应连接字符串并完成遥测初始化。

4. 自定义遥测配置(可选)

如果需要自定义遥测行为(比如调整采样率、添加自定义处理器),可以通过TelemetryConfigurationBuilder创建自定义配置bean:

import com.microsoft.applicationinsights.TelemetryClient;
import com.microsoft.applicationinsights.TelemetryConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppInsightsCustomConfig {

    @Value("${azure.application-insights.connection-string}")
    private String appInsightsConnString;

    @Bean
    public TelemetryConfiguration appInsightsTelemetryConfiguration() {
        return TelemetryConfiguration.builder()
                .connectionString(appInsightsConnString)
                .setSamplingPercentage(100.0) // 示例:设置全量采样
                // 可添加更多自定义配置,比如添加遥测处理器
                .build();
    }

    @Bean
    public TelemetryClient telemetryClient(TelemetryConfiguration configuration) {
        return new TelemetryClient(configuration);
    }
}

注意:此处使用的TelemetryConfiguration属于com.microsoft.applicationinsights包,是新版本SDK的类,替代了旧版com.microsoft.azure.applicationinsights下的同名类。

5. 验证配置有效性

启动应用后,可通过Azure门户查看对应Application Insights资源的遥测数据,确认当前环境的连接字符串已生效;也可查看应用日志,确认SDK初始化时未出现连接字符串相关的错误。

内容的提问来源于stack exchange,提问作者Sebastian Halik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:25:12