Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

51.

Elaborate ApplicationContext and it’s role in Spring Boot?

Answer»

ApplicationContext is an interface that extends BeanFactory. In addition to providing Dependency Injection, it also provides services like Aspect ORIENTED Programming (AOP), internationalization (i18n), EVENT HANDLING, etc. It is also referred to as the advanced container used by Spring for storing all the environmental information with regard to an APPLICATION being managed by Spring. It is read-only at run time but can be reloaded if necessary.

Spring recommends using ApplicationContext in all the scenarios, except when it is critical to the additional few KBs of memory that ApplicationContext consumes.

ApplicationContext provides the following abilities:

  • Bean factory METHODS for accessing application components.
  • To load file resources in a generic fashion.
  • To publish events to registered listeners.
  • To resolve messages to support internationalization.
52.

What is the difference between BeanFactory and ApplicationContext?

Answer»

BeanFactory is an INTERFACE that is the core of Spring’s Dependency Injection container. It is responsible for managing the components (beans), their dependencies and lifecycle.

BeanFactory can be configured using either a configuration XML file or by programmatically which is the case with Spring Boot. It creates a unique identifier for each Bean in the application.

BeanFactory is also called basic IOC, whereas ApplicationContext is called Advanced IOC. Although BeanFactory and ApplicationContext both are used to GET the beans from IOC container and inject them as per the configuration.

Below are the significant differences in implementation:

  1. BeanFactory uses lazy initialization i.e. it creates a singleton bean only when it is requested; whereas ApplicationContext uses eager initialization as it creates all singleton beans at the time of initialization.
  2. ApplicationContext creates and manages resources objects on its own whereas in the case of BeanFactory we need to explicitly provide the RESOURCE details.
  3. ApplicationContext supports internationalization but BeanFactory does not.
  4. Annotation-based dependency Injection is not supported by BeanFactory whereas ApplicationContext supports ANNOTATIONS like @PreDestroy, @Autowired, etc.
53.

What are Spring beans?

Answer»

Bean is used to REFER to any COMPONENT (POJO class) that is created and MANAGED by Spring’s Dependency Injection container. Ideally, a bean should adhere to the JavaBeans specification, but this is not mandatory, especially when using Constructor-based DI to wire the beans together. In general, any Spring-managed resource can be referred to as a bean which acts as the backbone of the application. Beans can be defined either by using XML configuration or by using Annotations like @Component, @SERVICE, @Controller, @Repository on top of the class definition.

A class can access beans either by injecting it directly or by injecting a bean that has defined a dependency on this bean.

The application can use beans without WORRYING about creating or destroying the objects.

BeanFactory is responsible for managing components, including their dependencies as well as their life cycles.

54.

What is Dependency Injection? What are the types of Dependency Injection?

Answer»

Dependency Injection (DI) is a pattern that implements Inversion of Control, removing the dependency from the code and instead have the framework or container deal with it. Dependency Injection makes code loosely coupled, which makes the application EASY to manage and test.

A typical Java application is composed of several objects that collaborate with each other to execute business logic. Traditionally each object is responsible for obtaining its own REFERENCE to the dependent objects. For example, a Service class will depend on the DAO class to get data from the database. Service class would directly create an instance of DAO class by using code like “new DAO()”. This introduces tight coupling between Service and DAO classes. This is where the Spring framework comes into rescue by removing tight coupling between the classes. In the above example, the Spring framework would inject a DAO object into Service class. This also allows us to replace the existing Database with another as and when required with minimal code changes.

Dependency Injection provides dependencies to objects at run time rather than compile time, hence making them loosely coupled. Using this concept PROGRAMMER does not create objects directly but describes how they should be created. The Code doesn’t need to connect the components and services together but just describe which services are needed by which components. Spring container will then hook them up.

Spring framework provides two mechanisms for dependency injection:

  • Constructor Based: It is implemented when a constructor of the class is defined with a number of arguments each representing a dependency on other class. The Spring container will inject the dependencies while invoking the class constructor at start-up.
  • Setter Based: It is implemented when a setter method is created for the dependency of the other class, HOWEVER, this method needs to be invoked explicitly.
55.

What is a Spring IoC container?

Answer»

Inversion of CONTROL (IOC) is a concept or principle where the control flow of a program is inverted i.e. instead of the program, the FRAMEWORK takes control of creating and proving objects as required. Spring IoC is responsible for creating the objects, wiring them as PER the configuration and managing the complete lifecycle from creation till destruction.

IoC can be implemented using two techniques namely Dependency Lookup and Dependency Injection.

Dependency Lookup is a traditional approach where a component must acquire a reference to a dependency. It helps in decoupling the components of the application but adds complexity in the form of the additional code that is required to couple these components back together to perform tasks.

This is the reason; Dependency Injection is considered a more viable and popular approach to implement IoC in Spring-based applications.

56.

Why is Spring Boot suitable for Microservices based cloud applications?

Answer»

With MONOLITHIC application development age, programmers and managers had the comfort of taking ample time for setting up the framework, dependencies and DEFINING all processes. However, in the era of microservices and with the agile development process, the expectation is to build the applications consistent and faster. Spring Boot project aims to solve this PROBLEM by providing intelligent defaults and embedded servers.

Spring Boot makes it easy to create standalone, production-grade Microservices applications that we can just run. It provides Starter Projects, which are a set of dependencies that we can include in the application. We get a one-stop-shop for all the Spring and cloud-related technologies like Spring Boot Starter Web for developing a web application or an application to expose restful services, Spring Cloud CONFIG, Spring Actuator, etc.

57.

How is Spring Boot different from Spring?

Answer»

Spring Boot has been built on top of Spring framework. By using it we can skip writing the boilerplate code like configuring the Database or Messaging Queues, XML CONFIGURATIONS, setting build path and maven dependencies. Spring Boot can be assumed as the upgradation of existing Spring functionalities to make it robust and easy to USE; that is required for building modern cloud applications.

Spring Boot PROVIDES an opinionated view by making certain elementary decisions while developing and running the application. Spring Boot uses sensible defaults, mostly based on the classpath contents. For example, Spring Boot sets up JPA Entity Manager Factory if JPA dependencies are in the classpath. However, it provides us the ability to override the defaults as and when required.

Another important aspect of Spring Boot is embedded servers. Traditionally, with Java web applications we build a WAR or EAR file and deploy them into servers like Tomcat or JBoss etc. Hence, we need to pre-install a web/application server before deploying the WAR/EAR files. Whereas in Spring Boot the web server (Tomcat or Jetty) is part of the application JAR. To deploy applications using embedded servers, it is sufficient if; Java is INSTALLED on the server.

Spring Boot is considered as the future of Spring, with most of the cloud-based Microservices being built on it. Most of the upcoming Spring projects are COMPLETELY integrated with Boot like example Spring Cloud Contracts, Spring Boot Admin, etc. required for cloud application development.

58.

Explain the difference between Embedded Server & War file.

Answer»

EMBEDDED Server(in context of Spring Boot) means a Web Server that comes in-built with Spring Boot. Spring Boot supports 3 web servers :

  • Tomcat (This is a DEFAULT web server): In FACT when you include Spring Boot web starter dependency, you get this without any more configuration.
  • Jetty: To override the default and include this, you can use spring-boot-starter-jetty dependency. At the same time, make sure you exclude tomcat web server dependency (default).
  • Undertow: This is another webserver supported by Spring Boot. To include this, you can use spring-boot-starter-undertow dependency.

If you would like to disable the web starter, you can do so by adding the following property to application.PROPERTIES :

spring.main.web-application-type=none

This is how you can customize/override various default properties associated with the webserver:

  • Port

You can override port by SPECIFYING it in application properties as :

server.port =8081

You can also override by including it as an environment variable(SERVER_PORT=8081).

To disable , HTTP port set :

server.port=-1

While, if you want to look for the best open port, use :

server.port=0

  • HTTP response Compression 

Use the following in property file :

server.compression.enabled=true

  • SSL

SSL can be configured by setting appropriate properties in application.properties file , for example :

server.ssl.key-store=classpath:keystore.jks

server.ssl.key-store-password=secret

server.ssl.key-password=another-secret

59.

Where do you define properties in Spring Boot Application? Explain different property formats supported.

Answer»

By default, application properties will sit inside src/main/resources of your Spring Boot Application. You can have multiple properties FILE, one per environment and one default properties file. 

For example, you may have :

application.properties           application-dev.properites application-int.properites          application-perf.properites application-uat.properites application-prod.properites

Now, depending on the value of Spring profile, the appropriate file would be selected for reference (along with with environment independent file, application.properties ). So what you get at any environment is a merger of application.properties and environment-specific properties. It means if the same property exists in the application.properties file, then the one from an environment-specific file will get higher precedence hence later overrides the former.

Spring boot supports properties, YAML or XML format. Spring Boot advocates 12-factor app principle of EXTERNALIZING the configuration. What it means, you can have these key-value pairs in external property repository and Spring Boot supports not only fetching the properties from those repositories but also refreshing the values when value changes at the repository.

There are 3 ways Spring Boot supports this:

1. Pull Approach 

In this approach, let’s CONSIDER your properties file are residing in the git repository ( True source of Properties file).  You can mark a property ready for a dynamic refresh ( without restarting the application) by using @RefreshScope.

(org.springframework.cloud.context.scope.refresh.RefreshScope).

You can use spring-cloud-config-server dependency to host these files to a server using a simple Spring Boot Application. In this spring boot application, you can use the following property to connect to the git repository:

spring.cloud.config.server.git.uri=https://github.com/your-repo/config-server-repo.git

And in actual application, make use of spring-cloud-starter-config dependency to connect your application to the server where these files are HOSTED. Your service will read these files from the hosted server. In your application, you need to provide the URL where these property files are   for example:

spring.cloud.config.uri=http://host1:8888

Whenever the value of any property goes, you can hit /refresh endpoint (provided by the actuator) on the application, this will be a POST request. Once the request is executed, the application will refresh all those properties marked for dynamic change will be refreshed.

2. Using a Push Approach 

In this approach, you use Spring-Cloud-Bus dependency and message broker ( let’s say RabbitMQ). Your config-server still points to the git repository. However, you use spring-cloud-starter-bus-amqp dependency to establish the communication between the config server & your application. This dependency NEEDS to be included in both, your application & Config Server.

60.

What are Spring Boot Starters?

Answer»

Spring Boot starters help you to avoid defining a set of dependency descriptors. Spring Boot Starters automatically includes the required dependencies for the said feature so that you don't have to go through the cumbersome process of defining the dependencies in your application. Beyond the EASE of dependency descriptors, it ALSO relieves you from a lot of boilerplate code. Thus, when you include the Starters you do not need to hunt through sample code and copy-paste dependency descriptors. Secondly, Spring Boot Starters also give you initial setup or initialization of the said feature. This enables the developer to get quickly started on the new feature.

Let’s try to understand this with an example:

You have a requirement to develop a new application that exposed REST endpoints for the user. It also has a requirement to connect to a DATABASE for fetching data. Let’s try to simulate this without Spring Boot first. In this case, you will need to add dependencies for Spring MVC, Jackson. You will also need to download and install Tomcat Web Server where you can deploy this new application. Additionally, you also need to configure Tomcat in your favourite IDE ( Eclipse or any other IDE) so that you can run the application from IDE itself.

So many things, right? With Spring Boot around, you can just add a dependency for Spring Boot Web Starter and you are done.

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId> </dependency>

You can annotate your classes with @RestController , @RquestMapping, @GET, @POST as Spring Rest library has been imported . You can just run application as Spring Boot mode and it will use embedded Tomcat Server to deploy your application , your application will be up and running at localhost:8080.

61.

What is Spring Boot CLI? Can you list out its advantages?

Answer»

Spring Boot CLI is a command-line ABSTRACTION that allows us to easily run Spring microservices expressed as GROOVY SCRIPTS. It also provides simplified and enhanced dependency management for those services.

Spring Boot CLI provides a feature called Shell from where you can execute commands. To start an embedded shell, run the following command:

spring shell

Now, if you want to run a groovy script called app.groovy then you can run it using the command :

run app.groovy

 Or if you WOULD like to know the spring version, the command is :

version

Advantages of using Spring Boot CLI :

  • It is an easy interface to run your Spring Boot application 
  • You can use it to test the Spring Boot application from the command prompt.
  • It has a Groovy compiler and Grape dependency manager.
  • Spring Boot Starter and AutoConfigurate components are used to resolve the dependencies and run the application.
  • Support for Groovy scripts without any INSTALLATION.
62.

How do you generate a Spring Boot based Project? What is the recommended approach?

Answer»

One of the ways to generate the Spring Boot based Project is using Spring Initializer. For this, visit https://start.spring.io/ and select appropriate parameters. This includes selecting build tool (Maven or Gradle), selecting the Language ( Java, Groovy or Kotlin), selecting the Spring Boot version, entering METADATA like Group name, artefact name, package name, java version, release artefact type (Jar, WAR) etc. There is a final section where you can select various Spring Boot Starters, for example, Web Starter or Security Starter

Once all this detail is filled in, you can click on Generate Project to GET a Zipped Spring Boot created.

An alternative to this is to use Spring Tools 4 for Eclipse ( IDE). With this, you can generate a Spring Boot Project direct inside IDE. From File MENU, click on New and then select other. Now look for Spring Starter Project, once found, click on it.

Now Click on Finish and a new Spring Boot Project will be created.

63.

Explain Different features of Spring Boot.

Answer»

FOLLOWING are the features of Spring Boot :

  • AutoConfiguration 

Spring Boot scans the libraries available on the also scans existing configuration for the given application and then provides default configuration ( going by convention) for the library with Application. Think of this as it actually initializes library on the classpath with default values. These libraries are nothing but Spring Boot Starters which may execute some code on startup as well.

For example, when you include a spring boot starter web dependency, from a coding point of view you will see spring mvc is available to you so that you can define REST endpoints or so, you can import @RestController, @RequestMapping etc to build REST endpoints for the application. 

However, from an application point of view, you will set that at startup, dispatcherservlet and a default error page is autoconfigured. What’s more, embedded Tomcat is configured to run at default port 8080 and application gets deployed at 8080. 

So see how Spring Boot MAKES life easy for Developers! 

Now, the DEVELOPER needs to think about SETTING up web.xml or setting up a Tomcat server. He/She can concentrate on an actual application which is drafting REST endpoints & writing Business Logic.

This example was with respect to Web dependency but the same is true for each and every dependency. This is helpful even in case of Proof of Concept carried out by Developers as configuration work is minimized because of AutoConfiguration.

  • Starters libraries

Spring Boot starter libraries is a list of dependency Starters that gets you (quick)        

started on using a particular feature in the application. A starter library is nothing but a wrapper built around the dependency libraries. It is a one-stop-shop for the feature & takes care of including the required dependencies.  It basically carries out 2 things for you :

  • First, of course, gets all the dependencies required ( Dependency Management for that Feature)
  • The Starters generally comes with initialization code assuming few defaults to get you started quickly.
Advantages of Using Spring Boot Starters :
  • The Dependency configurations & the starter itself are well tested and production-ready
  • Eases pom manageability
  • Decreases the Boilerplate code to a large extent
  • Decreases the application Configuration to a large extent.
  • Spring Boot Command Line interface

Spring Boot CLI lets you WRITE & run Groovy Scripts.

For example, let’s assume the following content in app.groovy

@RestController class GroovyScript { @RequestMapping("/") String home() { "Welcome to Spring Boot!" } }

You can then run this as 

spring run app.groovy

Visit localhost:8080 to see the Welcome Message.

  • Actuator

The actuator provides built-in features to your application which are production-ready. It provides web endpoints for each of this feature. Some of the most common Spring Boot Actuator endpoints:

  • /health: It shows application health information
  • /beans: It lists all Spring beans in your application
  • /trace: It shows trace information for last few HTTP requests
  • /env: Displays a list of properties in the current environment
  • /info: It shows arbitrary application info
  • /metrics: It shows all metrics related information for the current application
  • /threaddump: Performs thread dump.
64.

Explain how you will go about Security in Spring Boot Application?

Answer»

With a Spring Boot Application, you can fallback to Spring Security. Include the Spring Security Boot Starter :

<dependency&GT;     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-security</artifactId>     <version>2.1.6.RELEASE</version> </dependency> You can go with HTTP basic or form login.

To update the USERNAME or password , override the following properties in application properties FILE :

Spring.security.user.name = username1

Spring.security.user.password = password1

To enable method LEVEL security, you can use @EnableGlobalMethodSecurity.

To disable default Security configuration in-built, you need to exclude Security Auto Configuration class as follows :

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class }) public class SpringBootApplication1 {     public static void main(String[] args) {         SpringApplication.run(SpringBootApplication1.class, args);     } }

This can be also achieved by adding following to properties file :

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

@ConfigurationTo Override default Security you can implement WebSecurityConfigurerAdapter class , 

for example :

@EnableWebSecurity public class BasicConfiguration extends WebSecurityConfigurerAdapter {     @Override     protected void configure(AuthenticationManagerBuilder auth)       throws Exception {         auth           .inMemoryAuthentication()           .withUser("username")             .password("password1")             .roles("GUEST")             .and()           .withUser("admin")             .password("admin")             .roles("GUEST", "ADMIN");     }     @Override     protected void configure(HttpSecurity http) throws Exception {         HTTP           .authorizeRequests()           .anyRequest()           .authenticated()           .and()           .httpBasic();     } }

@EnableWebSecurity is optional if the default security configuration is disabled.

Oauth2 is COMMONLY used for authorization. To integrated OAuth2:

  • Add a starter for Oauth2
  • Use @EnableAuthrizationServer
  • Use @EnableResourceServer in an application where resource located 
  • On Client Side, use either of  @EnableOAuth2Sso or @EnableOAuth2Client.
65.

How do you make sure your changes are loaded without restarting the Spring Boot Application when running in Embedded Server mode?

Answer»

You can achieve this by adding a starter dependency for DEV tools.

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-devtools</artifactId>     <version>2.1.6.RELEASE</version> </dependency>

This is a very helpful feature in development, as it gives immediate feedback for code changes. This ENHANCES the productivity of developers to a great extent by saving time in restarts.

This is not a production-ready tool or feature and will be automatically disabled when RUNNING in production.

Applications using DevTools restart whenever a file on the classpath is modified.

Spring Boot DevTools PROVIDE the following additional features :

  1. You may need a way to configure global settings which are not tied to a particular application. Spring-boot-dev tools supports this by providing a global file is CALLED .spring-boot-dev tools.properties. You can store all such global settings in this file.
  2. Remote Debugging via HTTP :

To enable remote Debugging via HTTP, make sure you have following settings inside pom file 

<build>     <plugins>         <plugin>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-maven-plugin</artifactId>             <configuration>                 <excludeDevtools>false</excludeDevtools>             </configuration>         </plugin>     </plugins> </build>

Now when starting application , add following parameters to enable remote debugging :

-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n

To change port for debugger , add following to application.properties file ( configuration file ) :

spring.devtools.remote.debug.local-port=8010

The default debugger port is 8000.

66.

What is a Spring Boot Actuator? What are the features provided and how you can customize or add more?

Answer»

The ACTUATOR provides built-in features to your application which are production-ready. It provides web endpoints for each of this feature. Some of the most common Spring Boot Actuator endpoints:

  • /health: It shows application health INFORMATION.
  • /info: It shows arbitrary application info.
  • /metrics: It shows all metrics related information for the current application.
  • /trace: It shows trace information for last few HTTP requests.
  • /beans: It lists all Spring beans in your application.
  • /threaddump: Performs thread dump.
  • /env: Displays a list of properties in the current environment.

For example, when using MicroServices, you will definitely a health check for your microservice as your service registry/Load Balancer need to be updated with only LIVE or healthy services so that any incoming request to your application GOES to live node/server only. Instead of BUILDING your own health endpoint, you can just import the Spring Boot Actuator and use the built-in health endpoint.

If you need to your own health endpoint, you can do so by implementing health() method from org.springframework.boot.actuate.health.HealthIndicator.

To implement your own endpoint, you can implement org.springframework.boot.actuate.endpoint interface.

With Spring Boot Actuator 2.X, all endpoints except health and Info are disabled. To enable them you need to  set management.endpoints.web.exposure.include=*. 

67.

Can you explain Component Scanning in Spring Boot?

Answer»

If you use @SpringBootApplication annotation, it brings in default Component scan which will scan the root or base packages where your main class annotated with @SpringBootApplication is located and all its sub-packages. It will also consider your main class as one of the configuration CLASSES as it is annotated (IMPLICITLY) with @Configuration ( This is INCLUDED by @SpringBootApplication annotation).

This is equivalent to the following definition :

@Configuration @ComponentScan public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } }

Typically, in your application, you may want to limit the component scan to certain packages. You can achieve that by specifying the base package, for example,

@ComponentScan("com.example.demo.myapp")

This will scan for all Spring components inside com.example.demo.myapp package ( When we say Spring Components we mean Classes annotated with @Service, @Component, @Repository & @Controller etc.)

If you would like to scan multiple packages, it would be :

@ComponentScan({"com.example.demo.myapp1",”com.example.demo.myapp2”})

Type-safe alternative would be :

@ComponentScan(basePackageClasses = {com.example.demo.myapp1.Example1.class, com.example.demo.myapp2.Example2.class})

Here Example1.class acts as a marker class for package com.example.demo.myapp1 , when you specify this class , it will scan all other classes from the package com.example.demo.myapp1 along with Exmaple1.class. Similar is the CASE for myapp2 package.

@ComponentScan(basePackages = "com.mypackage",      includeFilters = @Filter(type = FilterType.REGEX, pattern="com.mypackage.*.*subpackage"),      excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = NotToBeScannedClass.class))

Here Regex FilterType is used for inclusion which means any class whose package matches the pattern (com.mypackage.*.*subpackage) will be included in the scan while using AssignableType Filter, we have SPECIFIED that a particular class should not be included in scanning.

@ComponentScan(basePackages = "com.mypackage",       includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyCustomAnnotation.class)})

MyAnnotation is defined as :

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { }

Here any class that is annotated with MyCustomAnnotation annotation will be included in the scan.

68.

Is it possible to have a Spring Boot Application without using @SpringBootApplication annotation? If yes, explain why would you do that?

Answer»

@SpringBootApplication annotation is not mandatory, it is possible to have a Spring boot based APPLICATION without using it.

You will do that when you don’t want to go with implicit features provided by @SpringBootApplication annotation.

SpringBootApplication annotation is defined as :

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication {

Let’s say you don’t want to use component scan in your application but would like to go with enabling feature that executes the code for DEPENDENCIES with default configuration (@EnableAutoConfiguration) 

You can probably define your class as :

@Configuration @EnableAutoConfiguration @Import({ MyConfiguration1.class, MyConfiguration2.class,MyConfiguration3.class }) public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } }

Here MySpringBootApplication is Spring boot based Application however it does not go with component scan instead it looks for specific configuration classes and import them to set up the configuration.

Another Application may use the following configuration :

@Configuration @ComponentScan(basePackages = "com.example.demo.components") public class MySpringBootApplication2 { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication2.class, args); } }

Here application wanted to AVOID using @EnableAutoConfiguration however it STILL wanted to components can feature hence MySpringBootApplication2 class definition includes that.

69.

Explain the main or entry-level method of Spring Boot Application.

Answer»

Main Spring Boot class typically looks like:

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

As you can see above, the main method calls static run() method SpringApplication class and provides itself(the SpringBoot1Application.class) & args. Now the class supplied (SpringBoot1Application.class) is annotated with @SpringBootApplication.

Now, SpringBootApplication annotation is defined as :

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication {

Where @SpringBootConfiguration is a wrapper Annotation over @Configuration.

Considering this, the Application will now look for classes annotated with @Configuration for setting up the configuration & context.

For example, a typical configuration might look like:

@Configuration public class MyConfiguration { @Bean public MyBean1 myBean() { return new MyBean1(); } @Bean public MyBean2 myBean() { return new MyBean2(); } @Bean public MyBean1 myBean() { return new MyBean1(); } }

This configuration creates and registers an instance of BEANS MyBean1, MyBean2 & MyBean3 so that they can be injected in your application classes and used. 

@ComponentScan instructs the application to scan all ( or filtered if configured so) to look for classes annotated with @Service, @Component, @REPOSITORY & @Controller and register them.

You can use include/exclude filters to narrow down the scan.

@EnableAutoConfiguration instructs the application to go with default configuration for the boot STARTERS. For example, the default port for the embedded tomcat server is 8080. 

So to summarize, at bootstrap, your application for @Configuration & initializes and registers configuration. It also looks for components in your packages using ComponentScan and registers them (Building the ApplicationContext). Finally, it executes CODE which initializes configuration with default configuration for the boot starters that you included.

70.

Why do you need Spring Boot

Answer»
  • Eases Development of Spring Based Applications
  • Eases Bootstrapping of Spring Based Applications
  • Eases Development, Unit Testing & Integration Test Process.
  • Provides opinionated STARTERS which simplify build & configuration
  • Uses Code by Convention to reduce a lot of boilerplate code and Configurations.

 For example, to create a web application using Spring, you will need the following maven DEPENDENCIES:

<dependency>      <groupId>org.springframework</groupId>     <artifactId>spring-web</artifactId>     <version>xxx</version> </dependency> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-webmvc</artifactId>     <version>xxx</version> </dependency>

While with Spring boot, it reduces to :

  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId>     <version>SPRING_BOOT_VERSION_xxx</version> </dependency>

Not only spring Dependencies, but you also get free Embedded Tomcat Servlet CONTAINER with this, you can override this with Jetty or Undertow.

Some of the commonly used are:

  • Spring-boot-starter-web
  • Spring-boot-starter-test
  • Spring-boot-starter-security
  • Spring-boot-starter-data-jpa
  • Spring-boot-starter-thymeleaf
  • spring-boot-starter-actuator
    • Provides default for Configuration ( Code & Annotations)
    • Reduces Development Time 
    • Increases Productivity
    • Eases integration with other Spring Components like Spring JDBC, Spring ORM, Spring Data, Spring Security, Spring Cloud etc
    • Eases testing of Java/Groovy applications from the command line by Providing Command-line Interface
    • Eases the creation of STANDALONE or Production-ready Applications
    • Provide inbuilt non-functional features ( Security, Embedded Servers, metrics, health checks, externalized configurations) 
    • Eases building of MICROSERVICES based Applications because of its easy integration with spring web, spring cloud etc
    • Eradicates XML configuration or keep it to a minimum.
71.

What is Spring Boot?

Answer»

Spring Boot is a FRAMEWORK built on top of Spring framework. It eases out configuring & setting up of applications. This is not true not only for standalone applications but also for web-based applications. It reduces boilerplate CODE and minimizes the spring configuration a lot.

It scans the libraries on its classpath and AUTOMATICALLY configures the required classes. This gets us STARTED without writing much code.

Most of the times, Spring boot sets up the default configuration for libraries on its classpath. If your requirement is different from default configuration & setup, Spring boot provides an easy way of overriding the defaults. For example, let’s say you have a Spring Data library on the classpath. In this case, Spring Boot automatically sets up a connection to Database along with Data Source class. Let’s say if you want to change the port where the database is running, Spring Boot provides an easy way of configuring or overriding it. You can set up those in the application.properties ( or YAML /XML).

Spring Boot also provides opinionated Spring-based third-party libraries. They are known as Starters. The advantage is that a starter has all third party dependencies included hence this minimizes the configuration in the application. SECONDLY, starters also provide default setup & configuration which eases out the integration of the library into the application and get started.

72.

What are the important annotation for Spring rest? What is the use case of this annotation?

Answer»
  • @RestController: Define at class level, so that spring CONTAINER will consider as RestENd point
  • @RequestMapping(value = "/PRODUCTS"): Define the REST URL for method level.
  • @PathVariable: Define as a method argument
  • @RequestBody: Define as a method argument
  • @ResponseEntity: To convert the domain object into the response format
  • @hasAuthority: To grant the access of corresponding endpoints 
  • @GetMapping: To make endpoint compatible for get request.
  • @PostMapping: To make endpoint compatible for POST request.
  • @PutMapping: To make endpoint compatible for put request.
  • @DeleteMapping: To make endpoint compatible for delete request.
  • @ResponseStatus: To generate the HTTP status.
  • @ResponseBody: To Generate the response message.
73.

What is a Spring-boot interceptor? Why do we need this features and is there any real use case scenario where spring boot interceptor fits?

Answer»

Spring boot interceptor is TYPICALLY used to INTERCEPT the request and response call MADE by the UI and microservices-based application, the need of this to add, filter, modified the information contain in request and response.

  • Interceptor in Spring Boot ONE can use to add the request header before sending the request to the controller 
  • Interceptor in Spring Boot can add the response header before sending the response to the client.
  • Spring boot works on the below TECHNIQUE
    • Before sending the request to the controller
    • Before sending the response to the client
    • After completing the request and response.

The real-world use case of spring-boot interceptor is authentication and authorization, where   we filter the information from the request which contain the credential information which use to authenticate and other information like role which require authorization. 

74.

What is Spring boot Initilizr?

Answer»

Spring BOOT Initilizr is a web application which use to generate the common TEMPLATES of spring boot application according to the configuration providing in the user interface.

  • Spring boot Initilizr provides a UI where we need to mention the below information.
  • Group
  • Artifact
  • Required dependencies
  • According to the above information, it creates a maven based spring boot PROJECT for ready to use.
  • Spring Initilizr also supports the gradle build tools.
  • Spring Initilizr supports the language such as Java, Groovy, Kotlin to develop the spring boot application.  
  • URL for spring Initilizr is https://start.spring.io/
  • Below is the User interface for same.

 All the CONFIGURATIONS mentioned at the TIME of generation of spring boot application will reflect in a pom.xml file, also provided the typical uniform architecture of the project

75.

What is Spring boot CLI?

Answer»

Spring boot CLI is a command line interface, which use and run test the microservices application based on spring boot.

  • Spring Boot CLI is a module of Spring boot application which use to run and test Spring Boot applications from the command prompt.
  • When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot Autoconfiguration COMPONENTS to resolve all dependencies and execute the application.
  • Internally contains GROOVY FILE which is a JAR Dependency Manager to add Spring Boot Defaults and resolve all dependencies AUTOMATICALLY
  • Spring Boot CLI operation is a combination of below component:
  • Auto Dependency Resolution 
  • Auto-Configuration
  • Management Endpoints
  • Embedded HTTP Servers

The benefits that we achieved from using spring boot CLI is, that we don’t need to use any import, no need to do the xml configuration, no web.xml and no dispatcherservlet declaration and no need to CREATE war file manually.

76.

What is a Spring boot starter?

Answer»

Spring boot starter comprises of templates which provide a Rapid Application Development, spring boot starter contains a COMBINATION of all the relevant transitive dependencies.  

  • Spring boot starter is a JAR file which predominantly solves the auto-dependency resolution in a spring boot application. 
  • Spring boot starter follows the unified pattern, like every dependency start with spring-boot-starter-X, where X will be the NAME of dependencies.  
  • For instance, if we add the dependency like spring-boot-starter-web, the spring boot starter will internally resolve and download all the ASSOCIATED dependencies, add to the application. 
  • Spring boot ALSO checks and resolves the transitive dependencies internally.

Below are some of the popular Spring boot starters:

  • Spring-boot-starter-web
  • Spring-boot-starter-mvc
  • Spring-boot-starter-security
  • Spring-boot-starter-jpa
  • Spring-boot-starter-tomcat
  • Spring-boot-starter-jetty
  • Spring-boot-starter-json
77.

What is an auto-configuration?

Answer»

SPRING boot autoconfiguration, check what are the jars that are AVAILABLE in the classpath, according to that autoconfiguration provides a basic configuration to the application according to that jars or library available.

  • Spring Boot autoconfigurator is used by Spring Boot Framework to provide “Auto-Configuration”.
  • Auto-configuration solves the problem of doing amount of configuration in Spring framework, it detects the dependency in a pom.xml file and according to that it CONFIGURES the spring boot application.
  • Below is the key annotation which we need to use to enable autoconfiguration

@EnableAutoConfiguration

  • We have a below option to enable the specific class to autoconfigure with the existing application.

@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

  • If we need to enable the external properties file, we can use the below annotation.

@EnableConfigurationProperties(MySQLDataSourceProperties.class)

  • Below annotation works when there is no bean available in the class PATH than its configure with configure bean class.

@ConditionalOnMissingBean

Spring boot autoconfiguration brings certain level of intelligence into the application so that it removes the hurdles to provide the configuration manually. ONE can debug the spring boot application by using the below approach:

  • Switch on the debug logging
  • Trigger the spring boot actuator 
78.

What are the basic components of spring boot?

Answer»

Below is the BASIC component, which plays a vital ROLE in spring boot FRAMEWORK for configuration, development, DEPLOYMENT, and execution of microservices based application.

  • Spring boot STARTER
  • Spring boot auto configurator.
  • Spring boot actuator.
  • Spring boot CLI.

Spring boot Initilizr.

79.

What is the important dependency of spring boot application?

Answer»

Below are the key dependencies which you need to add in MAVEN based or GRADLE based applications, to make the application compatible to use SPRING boot functionality. 

  • spring-boot-starter-parent
  • spring-boot-starter-web
  • spring-boot-starter-actuator
  • spring-boot-starter-security
  • spring-boot-starter-test
  • spring-boot-maven-plugin

These dependencies COME with ASSOCIATED child dependencies, which are also downloaded as a part of parent dependencies. 

80.

How spring boot work internally?

Answer»

Spring BOOT provides many abstraction layers to ease the development, underneath there are vital libraries which work for us. 

Below is the key function PERFORMING internally.

  • Using @EnableAutoConfigure annotation the spring boot application configures the spring boot application automatically. 
  • E.g. If you need MySQL DB in your project, but you haven’t configured any DATABASE connection, in that case, Spring boot auto configures as in memory database.
  • The entry point of spring boot application is a class which contains @SpringBootApplication annotation and has the main method.
  • Spring boot scan all the components included in the project by using @ComponentScan annotation.
  • Let’s say we need the Spring and JPA for database connection, then we no need to add the individual dependency we can simply add the spring-boot-starter-data-jpa in the project.
  • Spring boot follows the NAMING CONVENTION for dependency like spring-boot-starter. 

Considering above there are other internal functions which play a significant role in spring boot.

81.

Why do we encourage to use the spring boot over the other framework?

Answer»

Spring boot provides good compatibility with other spring frameworks which is used to provide the SECURITY, persistency features. Spring boot provides good support with docker containerization, which makes it a good choice to deploy the microservice based application and easy to maintain.

  • Provide the easiest way to configure the java beans.
  • Provide a powerful batch processing and MANAGE rest endpoints.
  • Provide auto-configuration mechanism, that means no manual configuration NEEDED
  • Provide annotation-based configuration, so no need to configure the xml file manually.
  • Ease the dependency management.
  • It includes the Embedded SERVLET container.  

Spring boot comes with spring cloud framework, which has many libraries which are used to HANDLE all types of nonfunctional requirement, which is usually not available in other frameworks.

82.

Why we should avoid the Spring boot framework?

Answer»

Besides advantages, there are few issues, where we should THINK about to adopt the SPRING boot framework to develop the microservice based architecture. 

  • Spring boot unnecessary increase the SIZE of the build with unused dependencies.
  • Not able to create the WAR file manually and difficult to configure externally.
  • Doesn’t provide much control and tuning the running build.
  • It’s only suitable for micro-services which eventually need to deploy in docker, but not large or mono lithics web services. 

Spring boot doesn’t provide good compatibility if we are integrating third party framework. 

83.

What are the key features of spring boot which makes Spring boot superior over the JAX-RS?

Answer»

There are significant advantages of using spring boot over the JAX-RS which is listed below.

  • Easy deployment
  • Simple scalability
  • Compatible with Containers
  • Minimum configuration
  • Lesser production time
  • Easy to understand, develop and configure the spring application
  • Increase the PRODUCTIVITY 
  • Reduce the development time.
  • Provide the health check and MONITORING feature.
  • Easy to orchestrate using docker.

All this advantage MAKES spring boot is one of best alternative to develop the MICROSERVICES application, along with one of the key benefits is, to make it compatible to use the other framework like messaging services, hibernate and spring CLOUD.

84.

What are the features of Spring boot providing to develop the microservices application?

Answer»

Spring boot is predominately used to develop the micros services-based application, most of the key features leverage to ease the configuration development and deployment of the microservices architecture.

  • Spring boot comes with the monitoring tool called as an Actuator which does the health CHECK of spring boot production application.
  • Externalised configuration 

@Value("${cassandra.password}")

private String password;

  • Embedded server’s support for example Tomcat, Jetty.
  • No need to deploy the war file, simply run it.
  • Provide convention over configuration using Auto-Configuration feature, example like below annotation.

@EnableAutoConfiguration

@ComponentScan 

  • Support Feign Integration which is basically an HTTP client. To enable this feature, we need to ADD the org.springframework.cloud:spring-cloud-starter-feign  MAVEN dependency.
85.

What is a Spring boot? How it benefits to develop the rest full web service?

Answer»

Spring Boot is an open SOURCE Java-based spring framework, which ease to develop a stand-alone and production ready micro service-based applications:

  • Spring boot is a combination of spring framework, embedded HTTP servers and configuration annotation

  • It follows “Opinionated Defaults Configuration” Approach to avoid lot of boilerplate code and configuration to improve Development, Unit Test and Integration Test Process.
  • Spring boot reduce Development, Unit Test and Integration Test time and to ease the development of Production ready web applications.
  • Spring boot comes with auto configuration, for instance, we must mention the dependency it will configure the spring boot accordingly, just we need to add the @EnableAutoConfiguration annotation
  • Spring boot support both Java and Groovy. 
  • Spring boot also support Spring Initializer to GENERATE the base project.
  • @SPRINGBOOTAPPLICATION annotation requires to configure the spring boot application.
  • Spring boot embedded HTTP server generally run on 8081 server port.

Spring boot ease and simplify the development of rest FULL web service and provide a quicker development technique by USING the key features provided by spring boot framework.