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:

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:

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:

Then add the Resources/ApplicationInsights.xml file:

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 DemoApplication.java file:

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:

Further Reading

https://docs.microsoft.com/en-us/azure/azure-monitor/app/java-get-started?tabs=maven