Spring Boot-Series Part 3: Deep Dive into Application Class

Welcome, this is the third part of the spring boot series.

If you haven’t read previous two parts yet, you can check below links:

What is Application Class?

Application class in Spring boot is used to bootstrap and launch the Spring application from a Java main method. This class automatically creates the ApplicationContext from the classpath, it scans the configuration classes and launches the application.

Let us take an example from our application (EmployeeRecords) which we setup in Part 1.

package com.thewebspark.EmployeeRecords;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(scanBasePackages = "com.thewebspark.EmployeeRecords")
public class EmployeeRecordsApplication {

	public static void main(String[] args) {
		SpringApplication.run(EmployeeRecordsApplication.class, args);
	}
	
}

In the above class, @SpringBootApplication annotation is used, which is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning.

It’s same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations as in Spring MVC or earlier spring boot versions.

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan

@SpringBootApplication adds all of the following:

  • @Configuration: It tags the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration: It tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
  • @ComponentScan: It tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

main() method

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application.

public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

As opposed to Spring MVC, there is no web.xml file, either. This web application is 100% pure Java and you do not have to deal with any other configurations.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s