Share this:

Top 85 Spring Boot Questions and Answers for Job Interview

1. What is Spring Boot?
Answer: Spring Boot is a JAVA-based framework used to build wen applications and enterprises. It offers a wide range of facilities that easily fulfill the modern business needs.

2. Mention the various advantages of Spring Boot.
Answer: The various advantages of Spring Boot are:
• Reduces development time and increase productivity.
• Very easy to build Spring Boot-based applications Groovy and Java
• Offers embedded HTTP servers of Tomcat, Jetty, etc. for development and testing of Web Apps.
• Provides many plugins for testing and developing of Web Apps made in Spring Boot
• Offered plug-ins work with in-memory and embedded databases
• Applications built with Spring Boot can be integrated with the likes of Spring ORM, Spring JDBC. Spring Data, etc.
• It offers the features of Command Line Interface for development and testing in JAVA and Groovy

3. Mention steps to change port in Spring Boot.
Answer: To change the default port in Spring Boot, the desired port number has to be used by the developer by accessing the properties of the server.port. The application.properties file or the <application.yml can be used to change the default port.

4. What do you know about the applications.properties?
Answer: The file extension used principally by Spring Boot is the application.properties file extension. It can be used for storing strings for internationalization and localization of strings. It can also be used for storing configurable parameters of an application.

5. List the steps used for making a Spring Boot Application.
Answer: Follow the given steps to create a Spring Boot Application:
• Open a terminal to make sure that valid versions of Maven and Java are installed in your system.
• Go to start.spring.io and choose the “Web” starter option from the provided dependencies searcher.
• The Spring Initialize documentation is used to create a new project structure to aid the coding process.
• Create the code in a suitable folder in the current directory.
• Create a Maven pom.xml file to build the project.
• Coding for the project is done in a text editor of the user’s preference.
• Once the working build has been initiated, it is tested by running the MVN package.
• The project is imported into a Java IDE that provides support for Maven at this stage.
• Add the desired classpath dependencies.
• Finish the spring boot application by creating a single Java file. Maven compiles sources attributed to src/main/java. Build the folder structure and add a file by the name src/main/java/Example.java for containing the code.
• The @RequestMapping and @RestController Spring MVC annotations are next used for the configuration of the application as desired by the project.
• Spring Boot auto-configures “Starter” applications but jar dependencies can also be chosen outside the starters to allow the process.
• The main method is then called to delegate the created application to Spring Boot’s SpringApplication class. The application is bootstrapped by SpringApplication that starts the Tomcat web server that has been auto-configured.
• Run the application by using the spring-boot-starter-parent POM.

6. List the steps used for debugging a Spring Boot Application.
Answer: Follow the given steps to know more about the debugging process of a Spring Boot Application:
• Start the Tomcat server instance in Eclipse.
• Open the Debug view once the server instance starts.
• Make sure that the application’s running threads are shown as a hierarchical tree-like structure in the view window.
• Find the application’s name at the top of the hierarchy.
• The application name must be shown in the Debug view even after the Tomcat server instance has stopped.
• Select the application name and right click on it.
• Choose the Edit Source Lookup.
• Choose the desired application root directory where Eclipse should look for the source code.
• Restart the Tomcat server instance.
• Once the instance shows up, you can debug the source code in spring boot.

7. What do you know about Spring Boot Annotations?
Answer: The Spring framework is an IOC container which promotes and implements the principles of dependency injection (DI) and control inversion (IOC). It permits developers to manage bean dependencies using XML-based configuration. These beans and their dependencies can also be defined using a Java-based configuration method that uses Spring annotations. This Java-based configuration approach creates programs for the management of bean components.

8. Mention the various types of Spring Boot Annotations.
Answer: The various types of Spring Boot Annotations are:
• @Conditional: It is a class that evaluates custom conditions in complex conditions and uses the annotation @Conditional.
• @SpringBootApplication: Used for marking the main class of any Spring Boot application, the @SpringBootApplication is known to encapsulate @EnableAutoConfiguration, @Configuration and the @ComponentScan annotations with their default properties and attributes.
• @ConditionalOnMissingBean and @ConditionalOnBean: These annotations are used to define conditions based on the absence or presence of specific beans.
• @ConditionalOnProperty: This annotation permits developers to make conditions on the basis of the values of properties.
• @ConditionalOnMissingClass and @ConditionalOnClass: Spring uses the marked auto-configuration beans when these conditions are used only if the class representing the argument in the annotation’s argument is either present or absent.
• @EnableAutoConfiguration: The @EnableAutoConfiguration makes the way for auto-configuration. Spring Boot looks for auto-configuration beans on the classpath of @EnableAutoConfiguration and applies them automatically.
• @ConditionalOnResource: This annotation allows the use of a definition when a specific resource is available.
• @ConditionalOnNotWebApplication and @ConditionalOnWebApplication: These annotations help in creating conditions considering whether a particular application is web-based or not.
• @ConditionalExpression: This annotation is used in more complex situations that are true/ false based on given conditions.

9. What do you know about Spring Boot Actuator?
Answer: The Spring Boot Actuator is used to provide additional features for monitoring and managing applications when pushed to production by developers. HTTP or JMX end points are usually used to achieve this.

10. How does the Spring Boot Actuator work?
Answer: The Spring Boot combines many additional features for monitoring and managing applications when pushed to production by the JMX or HTTP endpoints. Numerous production-ready features attributed to the Spring Boot are offered by the Spring Boot Actuator and the easiest way of enabling the features is by adding a specific dependency ‘Starter’ termed spring-boot-starter-actuator.

11. What is Spring Boot in Java?
Answer: Spring Boot is a framework designed for simplifying bootstrapping and development of new Spring applications. It showcases an opinionated approach for the easy configuration of applications and releases developers from the process of defining a boilerplate configuration.

12. What do you know about Spring Boot Transaction Management?
Answer: Transaction management is a very crucial part of any RDBMS-oriented enterprise application. It guarantees consistency and data integrity. An abstract layer is provided by the Spring framework along with various transaction management APIs. The transaction support system of Spring is meant to provide an alternative to several EJB transactions. It accomplishes this task by adding different transaction capabilities to POJOs. Both declarative transaction management and programmatic transaction management are supported by Spring Boot. Spring transaction management can be implemented even without an application server.

13. What do you know about @restcontroller in Spring Boot?
Answer: @RestController is a specialized version and convenience-based annotation of the controller. It is responsible for adding the @ResponseBody and @Controller annotations. When the controller class is annotated with @RestController annotation, the @ResponseBody annotation may can be excluded in the request mapping methods. The @ResponseBody annotation is active by default.

14. What do you know about @RequestMapping?
Answer: The @RequestMapping annotation is the most common annotation used in the repository of Spring Web applications. It maps HTTP requests for handling the methods of REST and MVC controllers.

15. What is @Qualifier?
Answer: This is used when more than a singular type of bean is created but only one needs to be wired with a property. The @Qualifier annotation is used along with @Autowired for removing any confusion and specifying the exact bean that has to be wired.

16. Mention the steps used to wire Spring Boot WAR to Tomcat.
Answer: Follow the given steps:
• Download Apache Tomcat.
• Unpack it into the desired Tomcat folder.
Answer: • Copy the WAR file from the target/spring-boot-tomcat.war into the tomcat/webapps/ folder.
• Go to tomcat/bin folder from a terminal.
• Execute the file.

17. What do you know about JPA?
Answer: JPA is an important Java object-relational persistence framework that is used for mapping processes. JPA is a standard in Java Persistence API.

18. How is JPA used in Spring Boot?
JPA focuses on utilizing JPA for the storage of data in relational databases in Spring Boot. One of the greatest features relates to the creation of repository implementations, which take place automatically. This is done at runtime and from a repository interface. Spring Data JPA can create an implementation when an application is runs.

19. What is CORS?
Answer: Cross-origin resource sharing or CORS refers to a W3C specification. It is applied by commonly-used browsers and helps users state flexible ways of authorizing cross domain requests. CORS serves as a substitute to less powerful and less secure hacks of IFrame or JSONP.

20. How is CORS enabled in Spring Bot?
Answer: Spring Boot Framework supports CORS so that it can offer better configuration as compared to what is possible through typical filter-based solutions.
• Global CORS configuration: When a global CORS configuration needs to be defined with annotation-based, fine-grained configurations, then the same has to be declared in Spring MVC and combined with @CrossOrigin configuration using filters. The GET, POST and HEAD methods, and all origins are permitted by default in this method of enabling CORS in Spring Boot.
• The Controller method of CORS configuration: The @CrossOrigin annotation can be added to the @RequestMapping handler method to enable CORS in Spring Boot. The @CrossOrigin allows all the HTTP methods and origins specified in @RequestMapping annotation for this.

21. What is Swagger?
Answer: Swagger is a specification in spring boot that is used for documenting REST API. It is important for specifying the method, URL, representation and other formats for describing the REST web services. It provides tools for generating /computing documentation from various application codes.

22. How do you add Swagger in Spring Boot?
Answer: Follow the steps to add Swagger in Spring Boot:
• Generation of swagger documentation with Spring Boot: A docket is configured and some dependencies linked to swagger are added to generate the swagger documentation. The Swagger UI provides visual representations of the documentation and helps in execution of test requests. The Spring configuration required for generating Swagger Documentation is: /src/main/java/com/in28minutes/springboot/rest/example/swagger/SwaggerConfig.java
• Viewing of the generated swagger documentation: Once the application has restarted, the swagger documentation can be viewed by going to URL http://localhost:8080/v2/api-docs. The Meta Information pertaining to the API can be found on top of the specific documentation.

23. What is docker?
Answer: Docker is a smart Linux container management toolkit. It has the nature of a container tool that allows easy deployment and running of applications using containers. They help developers create all-inclusive packages of developed applications with necessary dependencies.

24. Why is a docker used in Spring Boot?
Answer: The Docker helps users publish container images and use the container images that are published by others. They provide helpful means for running containerized processes necessary for building of Spring Boot applications.

25. What is Dev Tools?
Answer: The Spring Boot Dev Tools framework is a module used to provide powerful development tools. They shorten the development cycle to enable easy deployment and testing processes carried out during development. The developer-friendly features of Spring Boot Dev Tools can be added to a project once the build function has been performed.

26. What are the advantages of using Spring Boot for building out microservices?
Answer: The advantages can be listed as follows:
• It provides executable JAR packaging with useful dependencies.
• It provides production-ready services for building microservices.
• The Actuator features basic health-check and monitoring functions useful for microservices.
• Spring boot offers an embedded, pre-configured, Tomcat server.
• Spring boot offers opinionated views of the Spring Platform and third-party libraries. Developers can start with minimum efforts and get access to tools for creating standalone applications that are embedded with properties of Tomcat/Jetty/Undertow.
• It has minimal configuration overheads and can be customized for meeting the development needs of microservices.

27. How can we use h2 database?
Answer: Follow the given steps to know how to use h2 data base in Spring Boot:
• Visit https://start.spring.io/
• Click on ‘Generate Project’ after filling the artifactId, Group and dependencies (web /H2).
• A zip file ‘springBootAndH2DbIntegration’ will be downloaded.
• Extract files from the zip.
• Import the files in Eclipse as an existing Maven Project.
• Open the pom.xml file with an entry for H2 database. The h2 dependency has to be added to link with the H2 in-memory database. Search the H2 jar on the classpath. A data source will be automatically be created for connecting to the H2 database.
• Open ‘springBootAndH2DbIntegrationApplicaiton.java’.
• Run the given as a Java application.
• The embedded Tomcat Server is initiated and the application is deployed on Tomcat.
• The log shows that Tomcat has started on port 8080. Check if the SprigBootAndH2DbIntegrationApplication has started successfully.
• Open the web console of H2 with the following URL: http://localhost:8080/h2/.
• This shows that the H2 web console is running and is ready for connection to the H2 database.
• Click on the Test Connection button and check whether the connection is successful.
• Click on the Connect button to check whether the established database connection with h2 DB is ready for use.

28. What do you know about Starter Projects?
Answer: Starter Projects are a set of suitable dependency descriptors that can be included in any application.

29. What do you know about Spring Data?
Answer: Spring Data provides a familiar and consistent, Spring-based programming model for data access while retaining the special traits of the underlying data store. It is easy to use data access technologies, relational database and non-relational databases, map-reduce frameworks, and cloud-based data services.

30. What do you know about Spring Boot Starter?
Answer: Spring Boot Starters are JAR Files that are used by the Spring Boot Framework to provide auto-dependency resolution.

31. What do you know about the Spring Boot AutoConfigurator?
Answer: The Spring Boot AutoConfigurator is used by the Spring Boot Framework to provide Auto Configuration.

32. Write some components of the Spring Boot Framework.
Answer: Some of the components of the Spring Boot Framework are:
• Spring Boot Starter
• Spring Boot Actuator
• Spring Boot CLI
• Spring Boot AutoConfigurator
• Spring Boot Initilizr

33. Elaborate on Spring Boot Initilizr.
Answer: The Spring Boot Initilizr is a Spring Boot tool used to bootstrap Spring Boot or Spring Applications. It is available in Spring Boot in the following forms:
• Spring Boot Initilizr with IDE/IDE Plugins
• Spring Boot Initilizr with Web Interface
• Spring Boot Initilizr with Spring Boot CLI
• Spring Boot Initilizr with Third Party Tools

34. Elaborate on Spring Boot CLI.
Answer: Spring Boot CLI can be defined as a collection of auto-dependency resolution, auto-configuration, management EndPoints, embedded HTTP Servers(Jetty,Tomcat etc.) and (Groovy,Auto-Imports).

35. What is REST?
Answer: REST is used to expose HATEOAS RESTful resources around Spring Data repositories. Without writing a lot of code, we can expose RESTful API around Spring Data Repositories. The following code is an example:
@RepositoryRestResource(collectionResourceRel = “todos”, path = “todos”)
public interface TodoRepository
extends PagingAndSortingRepository<Todo, Long>

36. Why shouldn’t Spring Data Rest be used in practical?
Answer: With Spring Data REST, the database entitities are being exposed directly as REST Services. When RESTful services are designed, best design practices suggests that the interface used should consider two important things: Domain Model and Consumers. With Spring Data REST, none is considered. Only entities are exposed as REST Services. That is why it is suggested to use Spring Data REST only for quick prototyping or for the initial evolution of a project. It may not be a great idea for a fully evolved project.

37. While starting the boundary of a transaction start, which layer should be used?
Answer: Logic for business transactions is in the business/service layer and one would want to enforce transaction management at that level. Hence, transactions should be managed at the Service Layer.

38. What is the use of the Spring Boot Maven Plugin?
Answer: The spring-boot-maven-plugin provides a few commands which enables users to package the code as a JAR application or run the application. Read on to know more:
• Spring-Boot:Repackage is used for repackaging the JAR/WAR so that it can be executed.
• The Spring-Boot:Start and Spring-Boot:Stop is used to manage the lifecycle of the Spring Boot application.
• The Spring-Boot:Run is used to run the Spring Boot application.
• The Spring-Boot:Build-Info is used to generate build information that can be used by the Actuator.

39. List the differences between Hibernate and JPA.
Answer: The following are the differences between JPA and Hibernate:
• JPA is an interface/specification while Hibernate is one of the implementations of JPA.
• JPA uses annotations and interfaces from javax.persistence package without using the Hibernate import packages.
• Usage of JPA annotations is preferred over Hibernate because it is not connected to Hibernate annotations.

40. How to change the name of a package of a project in Spring Initializer?
Answer: To change the name of a package, click the link to ‘Switch to the full version’. Change the name to the desired package.

41. What happens when a Spring Boot Application is executed as a Java application?
Answer: If one is using Eclipse IDE, the Eclipse maven plugin ensures that as soon as a dependency is added or a change is made to the class file, it is compiled and is ready in the target folder. After that, the remaining process is just like any other Java application. When a Java application is launched, the spring boot auto configuration takes place. Tomcat is launched if the system sees that a Web Application is being developed.

42. What do you know about Auto Configuration?
Answer: Observe the following code:
<bean>
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix”>
<value>/WEB-INF/views/</value>
</property>
<property name=”suffix”>
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping=”/webjars/**” location=”/webjars/”/>
Spring Boot observes the Frameworks available on the CLASSPATH and the existing configuration for the application. Based on these, the Spring Boot provides basic configuration needed to configure the application with these frameworks. This process is known as Auto Configuration.

43. Mention the minimum baseline Java Version required for Spring 5 and Spring Boot 2.
Answer: The JAVA Version 8.0 or any advanced version is required for Spring 5 and Sprint Boot 2.

44. How does Spring Boot create production ready applications in quick time?
Answer: The Spring Boot enables production of ready applications iin quick time. It provides a few non-functional features like caching, monitoring, logging and embedded servers. The following are used to achieve this:
• Spring-Boot-Starter-Cache: It enables the Spring Framework’s caching support.
• Spring-Boot-Starter-Logging: it is used for logging logback.
• Spring-Boot-Starter-Undertow, Spring-Boot-Starter-Tomcat and Spring-Boot-Starter-Jetty: They are used to pick the specific choice of Embedded Servlet Container.
• Spring-Boot-Starter-Actuator: It is used to implement advanced features like monitoring and tracing of the application out of the box.

45. What are the Starter Project Options provided by Spring Boot?
Answer: Following is a list of the Starter Project Options provided by Spring Boot:
• Spring-Boot-Starter-Wen: Used for Web and RESTful applications.
• Spring-Boot-Starter-JDBC: Used for traditional JDBC.
• Spring-Boot-Starter-Data-JPA: Used for Spring Data JPA with Hibernate
• Spring-Boot-Starter-Security: Used for authentication and authorization using Spring Security.
• Spring-Boot-Starter-Data-Rest: It is used to expose simple REST services using Spring Data REST.
• Spring-Boot-Starter-Web-Services: It is used for SOAP Web Services.
• Spring-Boot-Starter-Hateoas: It is used to ass HATEOAS features to the application.
• Spring-Boot-Starter-Test: It is used for Integration and Unit testing.

46.How do users work with the path=”users”, collectionResourceRel=”users” and Spring Data Rest?
Answer: The given code shows the working:
@RepositoryRestResource(collectionResourceRel = “users”, path = “users”)
public interface UserRestRepository extends
PagingAndSortingRepository<User, Long>
The ‘path’ is the path segment under which resource has to be exported. The ‘collectionResourceRel’ refers to the rel value that has to be used when generating links to the collection resource. When HATEOAS links are generated, this is used.

47. Classify the dependencies in Spring Boot.
Answer: These are the following classification groups:
• WEB MVC: Spring MVC
• Validation: Validation API, Hibernate Validator
• Logging: slf4j, logback
• Jackson: used for JSON Binding
• Embedded Servlet Container: Tomcat
• Spring: beans, context, aop, core

48. Differentiate between GetMapping and RequestMapping.
Answer: The GetMapping is specific to the GET request method and is an extension of the RequestMapping to improve the clarity. The RequestMapping is generic and one can use it with PUT, POST, GET or any other request methods that use the method attribute on the annotation.

49. How to use @EnableCaching annotation with @Configuration or @SpringBootApplication annotations?
Answer: Follow the given code to understand the given:
@SpringBootApplication
@EnableCaching
public class SpringBootAppStarter {
public static void main(String[] args) {
SpringApplication.run(SpringBootAppStarter.class, args);
} }

50. How can one use the Jedis client with Spring Boot 2.x Redis?
Answer: The Spring Boot 2.0 starter spring-boot-starter-data-redis uses the Lettuce client. To use the Jedis client, we need to exclude the Lettuce dependency and include the Jedis.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
The Jedis dependency automatically resolves the commons-pool2 on the classpath.
To configure the Jedis pool we need to use spring.redis.* prefix with Jedis pool connection properties.

51. How can one use the Redis Cache in a Spring Boot Application?

Answer: Follow the given steps to implement the Redis Cache in your Spring Boot application:

Step 1: To get Redis connections, we can use either the Lettuce or the Jedis client libraries. The Spring Boot 2.0 starter ‘spring-boot-starter-data-redis’ resolves the Lettuce client by default. To get the pooled connection factory we need to provide commons-pool2 on the classpath. To work with Lettuce we need the following Maven dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

Step 2: The Redis properties are configured using the ‘spring.redis.*’ prefix in application.properties file.
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.lettuce.pool.max-active=7
spring.redis.lettuce.pool.max-idle=7
spring.redis.lettuce.pool.min-idle=2
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.shutdown-timeout=200ms
spring.cache.redis.cache-null-values=false
spring.cache.redis.time-to-live=600000
spring.cache.redis.use-key-prefix=true

Step 3: Enable cache using @EnableCaching annotation with @Configuration or @SpringBootApplication annotations.
@SpringBootApplication
@EnableCaching
public class SpringBootAppStarter {
public static void main(String[] args) {
SpringApplication.run(SpringBootAppStarter.class, args);
} }

52. How do we register a Listener in a Spring Boot application?

Answer: A Listener can be registered in many ways in a Spring Boot application.
Step 1: By using the ServletListenerRegistrationBean:
Create a ServletListenerRegistrationBean bean in JavaConfig and register the Listener. Follow the code for an example:
@Bean
public ServletListenerRegistrationBean<SessionCountListener> sessionCountListener() {
ServletListenerRegistrationBean<SessionCountListener> listenerRegBean = new ServletListenerRegistrationBean<>();
listenerRegBean.setListener(new SessionCountListener());
return listenerRegBean;
}
Step 2: Servlet listeners can also be registered in Spring Boot by annotating it with the Spring Boot annotation @Component.
@Component
public class SessionCountListener implements HttpSessionListener {
——
}
Step 3: One can also register servlet listeners using the @ServletComponentScan with @Configuration or @SpringBootApplicationannotations. The servlet listeners are annotated with @WebListener will be scanned by @ServletComponentScan.

53. How can we one register a Filter in a Spring Boot application?
Answer: A Filter can be registered in Spring Boot in more than one way.
Step 1: By using the FilterRegistrationBean:
Create a FilterRegistrationBean bean in JavaConfig and register our Filter.
@Bean
public FilterRegistrationBean<ABCFilter> abcFilter() {
FilterRegistrationBean<ABCFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new ABCFilter());
filterRegBean.addUrlPatterns(“/app/*”);
filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE -1);
return filterRegBean;
}
Step 2: By using @Component and @Order:
We can register a filter using @Component and set order using @Order.
@Order(Ordered.LOWEST_PRECEDENCE -1)
@Component
public class ABCFilter implements Filter {
——
}
Step 3: By Using the @ServletComponentScan:
To register a filter in Spring Boot, we can use the @ServletComponentScan annotation and the filter should be annotated with the @WebFilter annotation. We need to use @ServletComponentScan with @Configurationor @SpringBootApplication annotations. The @ServletComponentScan in Spring Boot will scan servlets annotated with @WebServlet, filters annotated with @WebFilter and listeners annotated with @WebListener only when using an embedded web server.

54. How can one register a Servlet in a Spring Boot application?
Answer: We can register Servlet in many ways in Spring Boot application. Suppose we have HelloCountryServlet.
Step 1: By using the ServletRegistrationBean:
Create a ServletRegistrationBean bean in JavaConfig and register Servlet. It works since Servlet 3.0.
WebConfig.java
@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean<HttpServlet> countryServlet() {
ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
servRegBean.setServlet(new HelloCountryServlet());
servRegBean.addUrlMappings(“/country/*”);
servRegBean.setLoadOnStartup(1);
return servRegBean;
}}
Step 2: By using the @ServletComponentScan:
The @ServletComponentScan in Spring Boot will scan Servlets annotated with @WebServlet annotation. The @ServletComponentScan is used with @Configuration or @SpringBootApplication annotations.
SpringBootAppStarter.java
@ServletComponentScan
@SpringBootApplication
public class SpringBootAppStarter {
public static void main(String[] args) {
SpringApplication.run(SpringBootAppStarter.class, args);
}}

55. How does one create a Spring Boot MVC application?
Answer: Resolve spring-boot-starter-web dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
When Spring Boot scans the Spring Web in classpath, it automatically configures Spring Web MVC.

56. Mention some of the properties present in the application.properties.
Answer: The following are the properties that can be found in application.properties:
• spring.mvc.async.request-timeout: Timeout in milliseconds for asynchronous request.
• spring.mvc.view.prefix: It configures the prefix for Spring view such as JSP.
• spring.mvc.media-types.*: It maps the file extensions to media type for content negotiation.
• spring.mvc.view.suffix: It configures the view suffix.
• spring.mvc.date-format: It configures the date format to be used.
• spring.mvc.favicon.enabled: It enables and disables favicon. Default is true.
• spring.mvc.locale: It provides the locale that has to be used.
• spring.mvc.servlet.load-on-startup: It configures the startup priority for Spring Web Services Servlet and the default value is -1.
• spring.mvc.static-path-pattern: It configures the path pattern for static resources.

57. How does one get the EntityManager in a Spring Boot application?
Answer: The following steps can be followed to get the EntityManager:
STEP 1: Resolve the following dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
STEP 2: Configure datasource in application.properties.
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/concretepage
spring.datasource.username=root
spring.datasource.password=cp
STEP 3: Use @PersistenceContext to get EntityManager.
@Repository
public class ArticleDAO {
@PersistenceContext
private EntityManager entityManager;
——
}

58. How does one use the @EnableJPARepositories in a Spring Boot Application?
Answer: The Spring Boot can automatically detect our repository if the package of that interface is the same or the sub-package of the class is annotated with the @SpringBootApplication annotation. If it is not used then we need to use the @EnableJpaRepositories annotation with the @SpringBootApplication annotation. By using the @EnableJpaRepositories one can configure the package name in which the required repository classes resides. For example, if the package of the required repository classes is com.cp.repository, the @EnableJpaRepositories can be used as shown.
@SpringBootApplication
@EnableJpaRepositories(“com.cp.repository”)
public class MyApplication {
——}
If we want to configure some specific classes, we need to use the basePackageClasses attribute of the @EnableJpaRepositories annotation. If one has a class ArticleRepository in the package com.cp.repository, then it can be configures using the repository basePackageClasses as shown.
import com.cp.repository.ArticleRepository;
@SpringBootApplication
@EnableJpaRepositories(basePackageClasses= {ArticleRepository.class})
public class MyApplication {
——}

59. Mention the steps used to include the JDBC template in any Spring Boot Application.
Answer: Follow the given steps to know how one implements the JDBC template in a Spring Boot Application:
Spring boot automatically detects the repository if the package of that interface is the same or sub-package of the class annotated with the SpringBootApplication. If that is not the case, then the @EnableJpaRepositories annotation is used with the @SpringBootApplication. Using the @EnableJpaRepositories, will configure package name in which the required repository classes resides. Suppose the package of the repository classes is com.cp.repository, one can use the @EnableJpaRepositories as shown below.
@SpringBootApplication
@EnableJpaRepositories(“com.cp.repository”)
public class MyApplication { ——}
If one wants to configure the specific classes then the basePackageClasses attribute of the @EnableJpaRepositories annotation has to be used. Suppose there is a class ArticleRepository in the package com.cp.repository, then one can configure the repository using the basePackageClasses as shown.
import com.cp.repository.ArticleRepository;
@SpringBootApplication
@EnableJpaRepositories(basePackageClasses= {ArticleRepository.class})
public class MyApplication { —— }

60. What is the Spring Boot Starter used for a SOAP web service?
Answer: To create a SOAP web service, we need to use the spring-boot-starter-web-services as shown:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
For the corresponding SOAP client we use the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>

61. How does a user work with the Spring Boot REST application?
Answer: To work with the Spring Boot RESTful web service, one needs to provide the spring-boot-starter-web Maven dependency as shown.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The above Maven dependency collects the Jackson JSON library i.e. the jackson-databind by default. Spring Boot REST gives JSON response by default because it detects the jackson-databind in its classpath.
To support the XML response in Spring Boot REST, we need to provide the jackson-dataformat-xml library with a spring-boot-starter-web.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.4</version>
</dependency>
The above dependency must be included in the pom.xml.

62. What are the different ways to run a Spring Boot application?
Answer: One can run a Spring Boot application in many possible ways.
1. By using a Maven Command: Go to the root folder of the project using command prompt and run the command.
mvn spring-boot:run
This executes the Spring Boot application in exploded form and useful in development phase.

2. Using Eclipse: Using command prompt, go to the root folder of the project and run.
mvn clean eclipse:eclipse
Refresh the project in Eclipse. This will set the classpath. Now execute the main() class by clicking Run as -> Java Application. This is useful in development phase.

3. Using Executable JAR: Using the command prompt, go to the root folder of the project and run the command.
mvn clean package
We will get executable JAR such as myapp.jar in target folder.

63. How is Jersey configured in a Spring Boot Application?
Answer: To configure Jersey in Spring Boot application, resolve the spring-boot-starter-jersey dependency as shown below.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

64. Mention some Jersey properties present in application.properties.
Answer: Some of the Jersey properties present in application.properties are as follows:
• spring.jersey.type: The value can be servlet or filter. Default value is servlet.
• spring.jersey.init.*: Init parameters that will be passed to Jersey servlet or filter.
• spring.jersey.application-path: Application path that acts as base URI. It overrides the value of @ApplicationPath.
• spring.jersey.filter.order: It defines the Jersey filter chain order. Default value is 0.
• spring.jersey.servlet.load-on-startup: Load on startup priority for Jersey servlet. Default value is -1.

65. Mention the ways that can be used to configure Spring Security in a Spring Boot application.
Answer: To work with the Spring Security one needs to include the spring-boot-starter-security in the Maven or Gradle file. If the spring security is in the classpath then the Spring Boot web applications are automatically secured by default, using basic authentication. A default username and random password will be displayed in console whenever the server starts and can be used for login authentication. The password is printed in console as follows.
Using default security password: 7e9850aa-d985-471a-bae1-25d741d4da23
The above password is random and changes whenever the server is restarted. By default, spring uses the in-memory authentication with a single user.
1. To enable Spring Security in Spring Boot application just use the following Spring Boot starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. To change the randomly chosen default password, the Spring Boot provides a security.user.password property that needs to be configured in the application.properties as shown below.
security.user.password= concretepage
Now one can login application using the user/concretepage credential.
3. If the user has a fine-tuned logging configuration, then the user needs to configure the given properties to print the randomly chosen default password in the application.properties with INFO level.
logging.level.org.springframework.boot.autoconfigure.security= INFO
4. The features such as HSTS, XSS, CSRF, caching are provided by default in Spring Security.

The above properties can be switched on and off using the security.*. However, if we want to use the username and password in the database, then we need to use the UserDetailsService. To control the security related configuration, we can create a security configuration class that will extend the WebSecurityConfigurerAdapter and then proceed to override the configure() method. This class will be annotated with the @Configuration and the @EnableWebSecurity annotations. If any user wants to enable the method level security, the configuration class will be annotated with the @EnableGlobalMethodSecurity.

66. Mention the security properties that can be changed using the security.* prefix in application.properties.
Answer: The security properties that can easily be changed using the security.* prefix in the application.properties is as follows:
• security.basic.enabled: It enables basic authentication and the stored default value is true.
• security.enable-csrf: It enables the CSRF and the pre-defined default value is false.
• security.user.role: It configures the role and the developer defined default value is USER.
• security.basic.path: It configures the paths to apply security and the user needs to provide comma separated paths.
• security.sessions: The predefined default value is stateless and values can be always stateless. If never requires, all values are stateless.
• security.user.name: It configures the user name and the stored default value is user.
• security.user.password: It configures the password.
• security.require-ssl: It enables as well as disables the SSL and the pre-stored efault value is false.

67. How is the datasource used by the Spring Boot application printed?
Answer: One can easily autowire the DataSource used in a Spring Boot application to get its instance. The given code snippet can be used to print the datasource using the CommandLineRunner.
SpringBootAppStarter.java
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootAppStarter implements CommandLineRunner {
@Autowired
DataSource dataSource;
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootAppStarter.class, args);
}
@Override
public void run(String… args) throws Exception {
System.out.println(“DataSource = ” + dataSource);
}}

68. Which Spring Boot starter is required to work with Database?
The spring-boot-starter-data-jpa is commonly used by most users to work with Spring Data. Follow the given code snippet to know more:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
For JDBC, some experienced developers and users also apply the spring-boot-starter-jdbc dependency. The given code can be onserved to understand this implementation.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

69. How can a user configure the JPA properties in a Spring Boot application using the application.properties?
Answer: In any Spring Boot application, all JPA properties can be very easily configured using the prefix spring.jpa.properties.* in the application.properties file.
The given code snippet tries to show this easy configuration:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.format_sql=true

70. Provide a piece of code to show how a user can configure a datasource by the application of the application.properties file.
Answer: The following piece of code can be used to show the configuration of a datasource by an application:
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/concretepage
spring.datasource.username=root
spring.datasource.password=cp
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=12
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=1200000
spring.datasource.hikari.auto-commit=true

71. How does a user configure a datasource using the application.properties file?
Answer: To connect with a database in any user-defined Spring Boot application, the user needs to include the spring-boot-starter-jdbc or the spring-boot-starter-data-jpa in the user-defined Maven or Gradle file. To configure the datasource properties, a user is required to use the prefix spring.datasource.* in the application.properties. The Spring Boot is designed in such a way that it detects driver class automatically.

72. How is a user supposed to use the Thymeleaf in a Spring Boot application?
Answer: The Thymeleaf is a server-side template engine that can be used to process XML, HTML, etc. To use the Thymeleaf with a user-defined Spring Boot application, the user is required to use the spring-boot-starter-thymeleaf in a specific Maven or Gradle file. If the Spring Boot scans the Thymeleaf library in classpath, it will automatically configure the Thymeleaf.

73. Mention the Maven dependency for Thymeleaf.
Answer: The given code snippet shows the Maven dependency for Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

74. Mention the properties present in the application.properties file that can be used to configure the Thymeleaf properties in a Spring Boot application.
Answer: The user is provided with the facility to change the default Thymeleaf configurations used to configure the Thymeleaf properties in the application.properties files. Some of the properties have been listed here:
• spring.thymeleaf.prefix: This is the value that is usually used to prepend with the view name to build the URL. The developer defines the default value to be classpath:/templates/.
• spring.thymeleaf.mode: The template mode that will be applied on the templates is implemented by using this. The default value for this property is HTML 5.
• spring.thymeleaf.suffix: This is the value that will be appended with the view name to build the URL. The pre-defined default value is .html.

75. How does one use profiles in a Spring Boot application?
Answer: Spring provides the @Profile annotation using what the user creates profiles. The @Profile annotation is used with the @Configuration annotation and the spring stereotypes such as @Component, @Service etc. Different profiles are created for different environments. In the development environment, the user can enable development profile and in the production environment, the user can enable production profile. A profile can be activated using the property file .properties/.yml, command line. The user can also create a default profile that will work when there is no active profile. To add an active profile to the property file, we need to configure the spring.profiles.active property. The user can also configure the profile using the spring.profiles.include that will be included for every active profile. When the user adds an active profile using command line then the active profile added in the property file is replaced with a profile added by the command line. The user can add active and default profile programmatically by using the ConfigurableEnvironment. In Spring Boot testing, the user can add active profile by using the @ActiveProfiles annotation. The user is also allowed to create a property file using a profile name using the convention application-{profile}.properties. The advantage of this approach is that the user can configure properties that are specific to a particular profile.

Suppose the user has a development profile, such as dev, then the user will have to create a property file such as the application-dev.properties and it can be activated in the following ways.
Step 1: By using the application.properties file.
spring.profiles.active=dev
Step 2: By using the command line.
java -jar -Dspring.profiles.active=dev myapp.jar
Step 3: By activating the profile programmatically.
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.setAdditionalProfiles(“dev”);
application.run(args);
} }

76. How is logging configured in the applications.yml?
Answer: The following snippet of code can be used to showcase how to configure logging in the applications.yml:
logging:
level:
org:
springframework:
security: DEBUG
hibernate: DEBUG
path: concretepage/logs
pattern:
file: ‘%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} – %msg%n’
console: ‘%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} – %msg%n’

77. How is a user supposed to configure logging by using the application.properties?
Answer: logging.level.org.springframework.security= DEBUG
logging.level.org.hibernate= DEBUG
logging.path = concretepage/logs
logging.pattern.file= %d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} – %msg%n
logging.pattern.console= %d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} – %msg%n
This code snippet can be used to demonstrate logging by using the application.properties file.

78. How does a user usually configure logging in any Spring Boot application?
Answer: The Spring Boot uses Logback, Log4J2 and Java util logging. By default, the Spring Boot uses Logback for its logging. By default, log is logged in console and can also be logged in files. The JAR dependency for Logback is resolved by the spring-boot-starter-logging. When the user uses any Spring Boot starter then the spring-boot-starter-logging is resolved by default. The user does not need to include it separately. If the Logback JAR is available in a classpath, then the Spring Boot will always choose Logback for logging. Thus, in order to use other logging such as Log4J2, the user is required to exclude the Logback JAR and add the Log4J2 JAR in classpath. To use the Logback logging, The user practically has to do nothing. The user just has to configure the logging level in the application.properties or application.yml files.
By default ERROR, WARN and INFO log level messages are logged in the console. To change the log level, the logging.level property has to be used. To get logs in a file, the user can configure the logging.file or the logging.path in a property file. Usually, the log files will rotate when they reach the ultimate limit of 10 MB.

79. What are the different properties that can be used to change the default logging?
Answer: The following properties are usually used to change the default logging in a Spring Boot application:
• logging.pattern.file: It defines the logging pattern in a file.
• logging.level.*: It is used as a prefix with a package name to set a log level.
• logging.file: It configures a log file name to log a message into a file. A user can also configure file names with an absolute path.
• logging.pattern.console: It defines the logging pattern in a console.
• logging.exception-conversion-word: It defines a conversion word when logging exceptions.
• logging.path: It only configures a path for a log file. Spring Boot creates a log file with the name spring.log.
• logging.pattern.level: It defines the format to render a log level. The developer defined default value is %5p.

80. How are the Spring Boot properties configured?
Answer: Spring Boot loads the application.properties and the application.yml files from a classpath by default. If both files are present in the classpath then both files have been loaded and merged into a similar environment. Using these files, the user can configure the required properties.
a. By using the property file application.properties
server.servlet.context-path = /spring-boot-app
server.port = 8585
b. By using the application.yml file
server:
servlet:
context-path: /spring-boot-app
port: 8585

81. How is the Tomcat Connection Pool configured by a user?
Answer: To use the Tomcat Connection Pool in the Spring Boot 2.0, the user is required to resolve the tomcat-jdbc dependency.
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
The tomcat-jdbc is used with either the spring-boot-starter-data-jpa or the spring-boot-starter-jdbc. In the 1.x version of Spring Boot, the user does not need to resolve the tomcat-jdbc and it is resolved by default by the spring-boot-starter-data-jpa and the spring-boot-starter-jdbc.
To configure the Tomcat specific connection pool settings, Spring Boot provides the spring.datasource.tomcat.* prefix.
The given snippet provides a sample usage of the various configurations used that can be used:
spring.datasource.type = org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.tomcat.initial-size=15
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=15
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true
spring.datasource.tomcat.test-on-borrow=false

82. How is the HikariCP configured in any Spring Boot application by any user?
Answer: In the 2.x version of Spring Boot, the JAR dependencies for HikariCP are resolved by default when using the spring-boot-starter-jdbc or the spring-boot-starter-data-jpa. However, if the user is using the Spring Boot 1.x, the user needs to include the HikariCP dependency.
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
In order to configure the Hikari specific connection pool settings, Spring Boot provides the spring.datasource.hikari.* prefix.
The given sample can be ibservec to understand the configuration of the HikariCP in a Spring Boot Aplication:
#Spring Boot 2.0 includes HikariDataSource by default
#spring.datasource.type = com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=12
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=1200000
spring.datasource.hikari.auto-commit=true

83. How can the context path in a Spring Boot application be changed by the user?
Answer: A user can change the context path by configuring the property server.servlet.context-path for the Spring Boot 2.x and the server.contextPath for Spring 1.x in a property file and in the command line as arguments with JAVA command.
server.servlet.context-path = /spring-boot-app
server.port = 8585
This code shows the configuration in Spring Boot 2.x.
• By using the JAVA command.
java -jar my-app.jar –server.servlet.context-path=/spring-boot-app –server.port=8585
• By changing the context path programmatically.
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
Map<String, Object> map = new HashMap<>();
map.put(“server.servlet.context-path”, “/spring-boot-app”);
map.put(“server.port”, “8585”);
application.setDefaultProperties(map);
application.run(args);
} }

84. How is the custom banner used in a Spring Boot application?
Answer: The custom banner can be used as follows:
• Text Banner: For the text banner, a file named as banner.txt is created with the desired text and keep it at the location src\main\resources.
• Image Banner: For the image banner, a file named banner.gif is created and kept at the location src\main\resources. Other file extensions that are commonly used are jpg, png, etc. The console used should also support to display the image.

85. What are the banner properties in the application.properties file that can be configured by the user?
Answer: The following banner properties can be configured in the application.properties file:
• banner.image.invert: It configures if the images should be inverted for dark terminal themes and the default value is false.
• banner.charset: It configures the banner encoding and the default is UTF-8
• banner.image.width: It configures the width of the banner image in char and the default value is 76.
• banner.image.location: It configures the banner image file location and the default is classpath:banner.gif. The file formats can also be jpg, png.
• banner.location: It is the banner file location and the default is classpath:banner.txt.
• banner.image.height: It configures the height of the banner image in char and the default is based on the image height.
• banner.image.margin: It is a left hand image margin in char and the default value is 2.

Spring Boot is one of the very popular and preferred open source Java-based framework used to create micro Services. Due to increasing popularity of architecture that supports micro services, Spring boot also has been gaining traction. As long as organizations chose Java platform an Spring framework to develop their applications, the demand for Spring boot skill will continue. 85 most common Spring Boot interview questions given above will help you to succeed in your job interview.

Share this: