DEV Community

Anil Kurmi
Anil Kurmi

Posted on

Spring Boot Interview Questions

List of top 20 Spring Boot Interview Questions and Answers

  1. What are the benefits of using Spring boot? How it is different from the Spring framework? Spring Boot makes it very easy to create a standalone application by providing auto configurations. It provides production-ready features like Actuator.

Features

Auto configuration
create standalone application with minimum fuss
Provide embedded tomcat, Jetty server
No need to deploy war file
No need to maintain the application/web server
Provide production-ready features such as metrics, JMX, health checks and Auditing.
Provide various starter to ease dependency management
Easy Integration with 3rd party libraries
Externalized Configuration
Profile specific properties file
Spring boot is an add-on for Spring framework. Spring Boot simplify the creation of application by auto-configuring it.

  1. What are few frequently used Spring Boot annotations?
    @SpringBootApplication : mark the main class of a Spring Boot application
    @SpringBootTest : used for Integration testing
    @Configuration : used to provide bean configrations
    @Conditional
    @ConditionalOnBean
    @Bean
    @DataJpaTest
    @WebMVCTest
    @Value
    @ControllerAdvice

  2. How to customize the environment or ApplicationContext before Spring boot application start?
    A SpringApplication class has ApplicationListeners and ApplicationContextInitializers that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations. It internally uses the META-INF/spring.factories.

There are many ways to register additional customizations:

I. Programmatically by calling the addListeners and addInitializers methods on SpringApplication before you run it.
II. Declaratively by setting the context.initializer.classes or context.listener.classes in application.properties.
III. Declaratively by adding a META-INF/spring.factories and adding jar files which application use as a library.

  1. How to create custom Spring Boot Auto Configuration? Auto-Configuration is the way Spring Boot configure the application automatically with minimal configurations. Auto-configuration classes can be bundled in external jars and picked-up by Spring Boot application. Auto-configuration can be associated to a “starter” dependencies that provide the auto-configuration code as well as the typical libraries that you would use with it.

Under the hood, auto-configuration is implemented with standard @Configuration classes. Additional @Conditional annotations are used to constrain when the auto-configuration should apply. Usually, auto-configuration classes use @ConditionalOnClass and @ConditionalOnMissingBean annotations. This ensures that auto-configuration applies only when relevant classes are found and when you have not declared your own @Configuration.

  1. How to disable the specific Auto-Configuration bean in Spring Boot? To exclude/disable the auto-configuration bean from being loaded to an application, we can add the @EnableAutoConfiguration annotation with exclude or excludeName attribute to a configuration class.

Another option to disable specific auto-configurations is by setting the spring.autoconfigure.exclude property from an application properties file.

  1. What is the Spring Boot Actuator? How to create custom Actuator? Actuators enable production-ready features to a Spring Boot application, without having to actually implement these things yourself. Actuator endpoints are secured by default. Here are some of the common endpoints of Spring Boot

/health — Shows application health information. It is often used by monitoring software to alert someone when a production system goes down.
/info — Displays arbitrary application info
/metrics — Shows ‘metrics’ information for the current application;
/trace — Displays trace information
/mappings — Displays a collated list of all @RequestMapping paths.
By default, all endpoints except for shutdown are enabled. In order to enable/disable the actuator endpoints, we can use its management.endpoint..enabled property. For example

management.endpoint.shutdown.enabled=true
Spring Boot automatically expose endpoints with@Endpoint, @WebEndpoint, or @WebEndpointExtension over HTTP using Jersey, Spring MVC, or Spring WebFlux. we can add a @Bean annotated with @Endpoint, any methods annotated with @ReadOperation, @WriteOperation, or @DeleteOperation are automatically exposed over JMX and, in a web application, over HTTP as well.

  1. How to configure the Logger in Spring Boot? How to change default logging level? Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. By default, if we use the Starters, Logback is used for logging.

Enable a debug mode by starting your application with a --debug flag.
$ java -jar myapp.jar — debug
From application.properties
debug=true
By default, Spring Boot logs only to the console and does not write log files. If we want to write log files, we can set alogging.file or logging.path property in your application.properties.

Changing the log level
logging.level.root=WARN
logging.level.com.myapp=DEBUG
logging.level.org.thirdpary.app=ERROR

  1. What are different approach available to load multiple external configuration/properties files? There are various ways we can provide load configuration files. Spring Boot properties are loaded in the following order. we can use one or more approach based on our requirement.

Command line arguments : $java -jar myapp.jar -Dspring.config.location=classpath:job1.properties,classpath:job2.properties com.app.MainClass

  1. Setting Java System properties (System.getProperties()).
  2. Setting up OS environment variables.
  3. Application properties outside of your packaged jar (application.properties including YAML and profile variants).
  4. Application properties packaged inside your jar (application.properties including YAML and profile variants).
  5. @PropertySource annotations on your @Configuration classes.
  6. Default properties (specified using SpringApplication.setDefaultProperties).
  7. Explain how Spring Boot Profiles works? How to configure multiple Profiles? Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. For example, we can use a separate profile for testing. Any @Component or @Configuration can be marked with @profile to limit when it is loaded.

@Configuration
@profile (“production”)
public class MySecurityConfiguration{
}
We can use a spring.profiles.active Environment property to specify which profiles are active.

spring.profiles.active=test
From the command-line, we pass the following parameters

$java -jar myapp.jar — spring.profiles.active=dev

  1. How to use the custom spring boot parent POM? Spring Boot provides the parent POM for easier creation of Spring Boot applications. The parent pom.xml takes care of dependency and plugin management.

In order to create custom parent POM, we can use the spring-boot-starter-parent as a dependency and customize the spring-boot-maven-plugin.


org.springframework.boot
spring-boot-dependencies
${springframework.boot.version}
pom
import

  1. How to change the default context path in Spring Boot? we can simply change the default context path by defining it in application.properties server.servlet.context-path=/rest/

we an also set the System Property, OS environement varialbe and from command line.

  1. How to depoy Spring Boot application as a WAR? spring-boot-maven-plugin added in ourpom.xmlautomatically tries to rewrite archives to make them executable by using the spring-boot:repackage goal. we can change the default packaging from pom.xml by

war
And, we initialize the Servlet context required by Tomcat context. we can implement the SpringBootServletInitializer interface.

@SpringBootApplication
public class MainClass extends SpringBootServletInitializer {
}

  1. How to change default server port in Spring Boot? By default, the embedded server start on port 8080. we can change it by defining it in the application.properties

server.port=8084
we can also change it dynamically by implementing WebServerFactoryCustomizer interface and passing it from the command line.

  1. How to customize the default Spring Security in Spring Boot? Spring Boot auto-configure the security by simply adding security starter dependency. The SecurityAutoConfiguration class contains various default auto configurations. By default, the Spring Boot will enable Basic Authentication security.

We can customize the Spring security by extending the WebSecurityConfigurerAdapter class and overriding configure method.

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
void configure(HttpSecurity http){
}
}

  1. How to disable the Spring Security in Spring Boot application? we can disable security auto-configuration by excluding the SecurityAutoConfiguration class from Spring Boot application.

@SpringBootApplication(exclude={SecurityAutoConfiguration.class})
public class SpringSecurityConfig{
}
we can also bypass the spring security by allowing all the requests

@Configuration
public class SpringSecurityConfig {
@Bean
public SecurityWebFilterChain filterChain(ServerHttpSecurity http){
http.authorizeExchange().anyExchange().permitAll();
return http.build();
}
}

  1. How to write the integration test in Spring Boot? Spring Boot provides a number of utilities and annotations to help when testing your application. Spring Boot provides a @SpringBootTest annotation for integration testing. The @SpringBootTest annotation works by creating the ApplicationContext used in our tests. @SpringBootTest provide various customization also.

@RunWith(SpringRunner.class)
@SpringBootTest
public class IntegrationTest{
}

  1. How to test only the database layer(JPA) in Spring Boot? We can use the @DataJpaTest annotation to test the database layer. By default, it configures an in-memory embedded database e.g. H2 database. It scans for @Entity beans, and configures Spring Data JPA repositories. Regular @Component beans are not loaded into the ApplicationContext. Also By default, data JPA tests are transactional and roll back at the end of each test.

@RunWith(SpringRunner.class)
@DataJpaTest
public class DatabaseTest{

}
We can inject a TestEntityManager bean, which provides an alternative to the standard JPA EntityManager that is specifically designed for tests. Similarly, Spring Boot provides @DataMongoTest annotation for MongoDB testing and @DataRedisTest annotation for Redis application testing.

  1. How to configure two databases and two EntityManager in Spring Boot? In order to use multiple databases in our application, we have to create our own DataSource bean.

Database 1

first.url = [url]
...

Database

second.url = [url]
....

@Bean("db1")
@Primary
@ConfigurationProperties(prefix="first")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}

@Bean("db2")
@ConfigurationProperties(prefix="second")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
Similarly, we can create multiple EntityManager by customizing bean. Spring boot provides EntityManagerBuilder for convenience.

@Bean("em1")
public LocalContainerEntityManagerFactoryBean em1(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(customDataSource1())
.packages(DataSource.class)
.build();
}

@Bean("em2")
public LocalContainerEntityManagerFactoryBean em2(
EntityManagerFactoryBuilder builder) {
return ...;
}

  1. How to customize the support for multiple content-negotiation for returning XML or JSON? We can overwrite configureContentNegotiation method in our WebMvcConfigurerAdapter configuration class.

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
....
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
}

And

produces = { "application/json", "application/xml" }

  1. How to register Servlet, Filter and Listener in Spring Boot? When using an embedded server, we can register servlets, filters, and the listeners by using Spring beans or by scanning for Servlet components.

we can use the FilterRegistrationBean bean to register a filter, ServletRegistrationBean to register Servlet and ServletListenerRegistrationBean to register Listener.

@Bean
public FilterRegistrationBean custFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
return registration;
}
https://practiceoverflow.com/take-test/sieWV1ypGBd7iBKoT3Nu/Spring-Boot-IQ-Test-2019:-contains-top-20-questions-to-practice-your-Spring-boot-knowledge

Top comments (0)