Spring Boot

1. What is Spring Boot?

Spring Boot is a preconfigured framework that works on top of the Spring Framework. It simplifies configuration for a Spring application by combining a group of common or related dependencies into single dependencies. Spring Boot is NOT a framework but rather, an easy way of creating stand-alone applications with little or no configurations.

SpringBootComponents

Spring Boot Starters is one of the major key features or components of the Spring Boot Framework. The main responsibility of Spring Boot Starter is to combine a group of common or related dependencies into single dependencies. We need to define a lot of dependencies in our build files. It is a very tedious task for a Developer.

spring-boot-starter-dependencies

Spring Boot is an opinionated framework that helps developers build stand-alone and production-grade Spring-based applications quickly and easily.

The primary goals of Spring Boot

  • Provide a radically faster and widely accessible getting-started experience for all Spring development.
  • Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
  • Provide a range of non-functional features that are common to large classes of projects, such as
    • embedded servers,
    • security,
    • metrics,
    • health checks,
    • externalized configuration
  • Absolutely no code generation and no requirement for XML configuration.

The key features include:

  • Spring Boot starters, easy dependency management
  • Spring Boot autoconfiguration, with sensible defaults
  • Elegant configuration management
  • Spring Boot actuator
  • Easy-to-use embedded servlet container support
  • ApplicationRunner or CommandLineRunner

ApplicationRunner or CommandLineRunner

Spring Boot allows you to execute code before your application starts. Spring Boot has the ApplicationRunner and the CommandLineRunner interfaces that expose the run methods. Both interfaces offer a single run method, which is called just before SpringApplication.run(…) completes.

CommandLineRunner exposes the public void(String... args) method

$ ./mvnw spring-boot:run -Drun.arguments="arg1,arg2"

ApplicationRunner exposes the public void run(ApplicationArguments args) method. if you want to have more control over the arguments, implement this interface.

$ ./mvnw spring-boot:run -Drun.arguments="arg1,arg2"
@SpringBootApplication 
public class SpringBootSimpleApplication implements CommandLineRunner, ApplicationRunner{

  public static void main(String[] args) throws IOException {
    SpringApplication.run(SpringBootSimpleApplication.class, args);
  }
  
  @Override 
  public void run(ApplicationArguments args) throws Exception {
    args.getNonOptionArgs()
      .forEach(file -> log.info(file)); 
  }
  
  @Override 
  public void run(String... args) throws Exception {
    for(String arg:args) {
      log.info(arg);
    } 
  }
}

2. What are the advantages of using Spring Boot?

  1. Spring Boot starters
    These starters are pre-configured with the most commonly used library dependencies so you don’t have to search for the compatible library versions and configure them manually. E.g., the spring-boot-starter-data-jpa starter module includes all the dependencies required to use Spring Data JPA, along with Hibernate library dependencies, as Hibernate is the most commonly used JPA implementation.

  2. Spring Boot autoconfiguration. Spring Boot configures various components automatically, by registering beans based on various criteria. The criteria can be:
    • Availability of a particular class in a classpath
    • Presence or absence of a Spring bean
    • Presence of a system property
    • Absence of a configuration file

    For example, if you have the spring-webmvc dependency in your classpath, Spring Boot assumes you are trying to build a SpringMVC-based web application and automatically tries to register DispatcherServlet if it is not already registered.

  3. Elegant configuration management
    • Spring supports externalizing configurable properties using the @PropertySource configuration
    • Spring Boot takes it even further by using the sensible defaults and powerful type-safe property binding to bean properties
    • Spring Boot supports having deparate configuration files for different profiles without requiring much configuration.
  4. Spring Boot actuator. It provides a wide variety of such production-ready features:
    • Can view the application bean configuration details
    • Can view the application URL mappings, environment details, and configuration parameter values
    • Can view the registered health check metrics
  5. Easy-to-use embedded servlet container support.
    It creates a JAR type module and embed the servlet container in the application to be a self-contained deployment unit.

3. Why is it “opinionated”?

It makes assumptions and configures things for your application based on the dependencies in your classpath. By doing this, developers don’t have to waste time on configuration but instead, use their time on developing features.

  • It follows the “Convention Over Configuration” approach.
  • It pre-configures Spring app by reasonable defaults.
  • It’s highly customizable

Most of Spring application configuration is based on a common application.properties or application.yml file. If none is specified, it already has those property’s values as defaults.

4. What things affect what Spring Boot sets up?

Starters that are added to dependencies – only if @EnableAutoConfiguration or @SpringBoot application are used.

  • Spring applications need complex configuration
  • Spring Boot addresses the problem by eliminating the need to manually set up the boilerplate configuration.
  • Spring Boot takes an opinionated view of the application and configures various components automatically, by registering beans based on various criteria. The criteria can be:
    • Availability of a particular class in a classpath: @ConditionalOnClass, on the other hand @ConditionalOnMissingBean
    • Presence of a system property
    • Absence of a configuration file
    • Presence or absence of a Spring bean @ConditionalOnBean@ConditionalOnMissingBean

How does it work? How does it know what to configure?

It scans dependencies in the classpath and then initializes “maybe” required beans. For example, if you have spring data on your classpath, then Spring Boot will create JPA repository bean.

Spring Boot provides many custom @Conditional annotations to meet developers’ autoconfiguration needs based on various criteria, each of which can be used to control the creation of Spring beans.

  • A specific class is present in the classpath
  • A Spring bean of a certain type isn’t already registered in the ApplicationContext
  • A specific file exists in a location
  • A specific property value is configured in a configuration file
  • A specific system property is present/absent
  • Example:
    • @ConditionalOnClass
    • @ConditionalOnMissingClass
    • @ConditionalOnBean
    • @ConditionalOnMissingBean
    • @ConditionalOnProperty
    • @ConditionalOnResource
    • @ConditionalOnWebApplication
    • @ConditionalOnNotWebApplication

5. How are properties defined? Where is Spring Boot’s default property source?

Properties are usually defined in property files. Spring Boot default property source is application.properties or application.yml

6. Would you recognize common Spring Boot annotations and configuration properties if you saw them in the exam?

Spring Boot annotations include:

  • @SpringBootAnnotation – is sum of 3 annotation: @Configuration, @EnableAutoConfiguration, @ComponentScan
  • @EnableAutoConfiguration

7. What is the difference between an embedded container and a WAR?

An embedded container is a server that comes with the resulting application whereas WAR is an archive that can be deployed on an external container.

Standalone app uses your resources, web app executes on the server, rendering is done on your system.

An embedded container is packaged in the application JAR-file and will contain only one single application.

WAR-file will need to be deployed to a web container, such as Tomcat, before it can be used. The web container to which the WAR-file is deployed may contain other applications.

Deployable WAR

  1. The first thing you do is change the packaging type.
    • <packaging>war</packaging> in Maven
    • apply plugin: 'war' in Gradle
  2. you need to add spring-boot-starter-tomcat as the provided scope so that it won’t get packaged inside the WAR file.

  3. Finally, you need to provide a SpringBootServletInitializer sub-class and override its configure() method. You can simply make your application’s entry point class extend SpringBootServletInitializer.
    @SpringBootApplication 
     public class SpringbootWebDemoApplication extends SpringBootServletInitializer {
    
       @Override 
       protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
         return application.sources(SpringbootWebDemoApplication.class); 
       }
     }
    

    Now running the Maven/Gradle build tool will produce a WAR file that can be deployed on an external server.

8. What embedded containers does Spring Boot support?

  • Tomcat,
  • Jetty,
  • Undertow servers.

Use Jettry rather than Tomcat

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</dependencies>

 

 

9. What does @EnableAutoConfiguration do?

@EnableAutoConfiguration – turns on Spring Boot autoconfiguration. It auto-configures the beans that are present in the classpath. This simplifies the developer’s work by guessing the required beans from the classpath and configure it to run the application. This annotation is part of the spring boot project.

For example, if you have the tomcat jar file in the classpath, then Spring Boot will configure the tomcat server. As a developer, you don’t have to do anything.

Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration.

It’s a Spring Boot specific annotation. It enables the autoconfiguration of Spring ApplicationContext by:

  1. scanning the classpath components and
  2. registering the beans that match various conditions.

Spring Boot provides various autoconfiguration classes in spring-boot-autoconfigure{version}.jar, and they are typically:

  1. annotated with @Configuration to mark it as a Spring configuration class and
  2. annotated with @EnableConfigurationProperties to bind the customization properties and one or more conditional bean registration methods.

10. What about @SpringBootApplication?

@SpringBootApplication does 3 things: 

  1. turns on autoconfig
  2. enables auto-scanning
  3. defines a configuration class

The package of the class that is annotated with @EnableAutoConfiguration, usually via @SpringBootApplication, has specific significance and is often used as a ‘default’. For example, it will be used when scanning for @Entity classes. It is generally recommended that you place @EnableAutoConfiguration (if you’re not using @SpringBootApplication) in a root package so that all sub-packages and classes can be searched.

It’s a top-level annotation designed to use only at class level. It’s a convenience annotation that equivalent to declaring the following three:

  1. @EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism

  2. @ComponentScan: enable @Component scan on the package where the application is located

  3. @Configuration: allow to register extra beans in the context or import additional configuration classes

11. Does Spring Boot do component scanning? Where does it look by default?

Yes, Spring Boot does component scanning. Spring Boot scans all sub-packages from the root package. It also scans packages that have at least one configuration class.

  • @ComponentScan or @SpringBootApplication enables component scanning.

  • If no component scanning attribute defined, it will scan only the package in which the class annotated.

  • The base package(s) which to scan for components can be specified using the basePackages element in the @ComponentScan annotation or by specifying one or more classes that are located in the base package(s)

@SpringBootApplication(scanBasePackageClasses = HelloWorld.class)
public class OrdersDBConfig {}



@Configuration 
@EnableAutoConfiguration 
@ComponentScan(basePackages = "com.mycompany.myproject") 
@EntityScan(basePackageClasses=Person.class) 
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  } 
}

 

12. What is a Spring Boot starter POM? Why is it useful?

Starter POM is a set of dependencies that work as some templates for dependencies used for different tasks.

Starter POMs are that all the dependencies needed to get started with a certain technology have been gathered.

A developer can rest assured that there are no dependencies missing and that all the dependencies have versions that work well together.

All official starters follow a similar naming pattern: spring-boot-starter-*, where * is a particular type of application.

Spring Boot supports both Java properties and YML files. Would you recognize and understand them if you saw them?

Java properties files come in application.properties file; YAML come in application.yml

Can you control logging with Spring Boot? How?

Yes. First you add the required dependencies to the classpath and then configure the required framework using application.properties or framework-specific configuration file placed in the classpath.

Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl module.

Spring Boot uses Commons Logging internally by default, but it leaves the underlying implementation open.

Default configurations are provided for

  • Java Util Logging,
  • Log4J2, and
  • Logback

By default, if you use the “Starters”, Logback is used for logging.

By default, ERROR, WARN, and INFO level messages are logged. In application.properties add: debug=true to enable debug level logging.

Logging is initialized before the application context, so it is impossible to control logging from using @PropertySources in @Configuration classes.

System properties and conventional Spring Boot external configuration files should be used. Depending on the logging system that is used, Spring Boot will look for the specific configuration files.

The logfile name to use by default by Spring Boot can be configured using the logging.file Spring Environment variable.

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

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