Integrate Application Insights into a Spring Boot Application

To get started, we’ll set up a basic Spring Boot application, and then add Application Insights in the next step.

Creating a Skeleton Spring Boot App

To get started, go to Spring Boot Initializr and create an app with the following selected:

  • Create a gradle project
  • Add the Spring Web dependency

Once that’s done, extract the archive file given and open in your Java IDE of choice (IntelliJ, for example).

Add the following Controller ApiController.javato add an API endpoint:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class ApiController {

    public String doGet() {
        return "Hello World!";

Start the application using clean, build, and bootRun. You can verify the endpoint is working with a tool such as Insomnia and calling at http://localhost:8080 to have “Hello World!” displayed.

Once you have this working, you’re ready to start integrating Application Insights to provide analytics.

Integrating Application Insights

First, add the Application Insights dependencies to your build.gradle file:

dependencies {
    ...  // other dependencies
    compile group: '', name: 'applicationinsights-web-auto', version: '2.5.0'

Then add the Resources/ApplicationInsights.xml file:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="" schemaVersion="2014-05-30">
   <!-- HTTP request component (not required for bare API) -->
      <Add type=""/>
      <Add type=""/>
      <Add type=""/>

   <!-- Events correlation (not required for bare API) -->
   <!-- These initializers add context data to each event -->
      <Add type=""/>
      <Add type=""/>
      <Add type=""/>
      <Add type=""/>
      <Add type=""/>


Finally, you’ll add the section in startup to add the App Insights Instrumentation Key to the codebase, to link the resource to send data to. A quick note on this – you can add the key to the .xml file, but I prefer to add it in as an environment variable, so this can be changed across different environments when deployed.

Add the following method to the file:

private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);


	private void init() {
		String appInsightsKey = System.getenv("AppInsightsKey");
		if (appInsightsKey == null) {
			log.warn("App Insights Key not provided, no analytics will report.");


Verifying in App Insights

With the changes made in place, the last step is verifying everything is in place. To start the application with App Insights enabled:

  • Add the App Insights Instrumentation Key to an environment variable called AppInsightsKey.
  • Start the application.
  • Call the endpoint at http://localhost:8080
  • View the results at the App Insights screen.

Further Reading

Leave a Reply

Your email address will not be published. Required fields are marked *