Spring Boot Interview Questions : Part 1 | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

1. Spring Boot

  • It is a framework which was built on the top of Spring framework. Spring Boot is supported to 3 different programming languages Java, Kotlin, Groovy. Even though if you are using Kotlin, Groovy, Java those are converted into byte code only, that is executed on the Java Runtime Environment (JRE).
  • Spring Boot 1.X -> upto Java 7 version only, only supports to synchronous programming
  • Spring Boot 2.X -> min Java 8 and support to latest version of Java, supports to asynchronous programming

2. difference between Spring, Spring MVC and Spring Boot.

Spring: Spring Framework is the most popular application development framework of Java. The main feature of the Spring Framework is dependency Injection or Inversion of Control (IoC). With the help of Spring Framework, we can develop a loosely coupled application.

Spring MVC: Spring MVC is a Web MVC Framework for building web applications. It contains a lot of configuration files for various capabilities. It is an HTTP oriented web application development framework.

Spring Boot: Spring Boot is a module of Spring Framework. It allows us to build a stand-alone application with minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or RESTful services. Spring Boot makes it easy to quickly bootstrap and start developing a Spring-based application. It avoids a lot of boilerplate code. It hides a lot of complexity behind the scene so that the developer can quickly get started and develop Spring-based applications easily.

Spring VS Spring Boot:

SpringSpring Boot
Spring Framework is a widely used Java EE framework for building applications.Spring Boot Framework is widely used to develop REST APIs.
It aims to simplify Java EE development that makes developers more productive.It aims to shorten the code length and provide the easiest way to develop Web Applications.
The primary feature of the Spring Framework is dependency injection.The primary feature of Spring Boot is Autoconfiguration. It automatically configures the classes based on the requirement.
It helps to make things simpler by allowing us to develop loosely coupled applications.It helps to create a stand-alone application with less configuration.
The developer writes a lot of code (boilerplate code) to do the minimal task.It reduces boilerplate code.
To test the Spring project, we need to set up the sever explicitly.Spring Boot offers embedded server such as Jetty and Tomcat, etc.
It does not provide support for an in-memory database.It offers several plugins for working with an embedded and in-memory database such as H2.
Developers manually define dependencies for the Spring project in pom.xml.Spring Boot comes with the concept of starter in pom.xml file that internally takes care of downloading the dependencies JARs based on Spring Boot Requirement.

Spring MVC VS Spring Boot:

Spring MVCSpring Boot
Spring MVC is a model view controller-based web framework under the Spring framework.Spring Boot is a module of Spring for packaging the Spring-based application with sensible defaults.
It provides ready to use features for building a web application.It provides default configurations to build Spring-powered framework.
It requires build configuration manually.There is no need to build configuration manually.
A Deployment descriptor is required.There is no requirement for a deployment descriptor.
It specifies each dependency separately.It avoids boilerplate code and wraps dependencies together in a single unit.
It takes more time to achieve the same.It reduces development time and increases productivity.

3. Advantages of Spring Boot

  1. It is very easy to develop Spring Based applications with Java or Groovy.
  2. It reduces lots of development time and increases productivity.
  3. It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
  4. It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
  5. It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
  6. It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
  7. It provides CLI (Command Line Interface) tool to develop and test Spring Boot (Java or Groovy) Applications from command prompt very easily and quickly.
  8. It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle
  9. It provides lots of plugins to work with embedded and in-memory Databases very easily.

4. @SpringBootApplication Annotation

  • Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It’s same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.
@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 {
    ...
    ...
}

5. Components of Spring Boot

  1. Starter – Its a one time shop for the programmer to declare all required dependencies for the module in single go.
  2. Autoconfiguration – applicationContext.xml or preparing @Configuration classes to perform configuration setup for the spring module.
  3. CLI – used by Groovy developers to prepare groovy scripts as Spring Boot.
  4. Actuator – It provides post production support for our application

6. Why the name is given as Spring Boot?

  • Spring -> It is built on top of the spring framework
  • Boot -> It performs autoconfiguration for the spring module.

7. Spring Boot Starters

  • Dependency management is a critical aspects of any complex project. And doing this manually is less than ideal; the more time you spent on it the less time you have on the other important aspects of the project.
  • Spring Boot starters were built to address exactly this problem. Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors.
  • Benefits of using Spring Boot starters
    • Increase pom manageability
    • Production-ready, tested & supported dependency configurations
    • Decrease the overall configuration time for the project
  • The actual list of starters can be found here.

8. Spring Configuration Bootstrap vs Application Properties

When Is the Application Configuration File Used?

  • We use application.yml or application.properties for configuring the application context.
  • When a Spring Boot application starts, it creates an application context that doesn’t need to be explicitly configured – it’s already autoconfigured. However, Spring Boot offers different ways to override these properties.
  • We can override these in code, command-line arguments, ServletConfig init parameters, ServletContext init parameters, Java system properties, operating system variables, and application properties file.
  • An important thing to keep in mind is that these application properties files have the lowest precedence compared to other forms of overriding application context properties.

When Is the Bootstrap Configuration File Used?

  • We use bootstrap.yml or bootstrap.properties for configuring the bootstrap context. This way we keep the external configuration for bootstrap and main context nicely separated.
  • The bootstrap context is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files.
  • When the Spring Cloud application starts, it creates a bootstrap context. The first thing to remember is that the bootstrap context is the parent context for the main application.
  • Another key point to remember is that these two contexts share the Environment, which is the source of external properties for any Spring application. In contrast with the application context, the bootstrap context uses a different convention for locating the external configuration.
  • The source of configuration files can be a filesystem or even a git repository, for example. The services use their spring-cloud-config-client dependency to access the configuration server.
  • To put it in simple words, the configuration server is the point through which we access the application context configuration files.

9. @Profile annotation

  • Using the @Profile annotation – we are mapping the bean to that particular profile; the annotation simply takes the names of one (or multiple) profiles.
  • Consider a scenario where we have to maintain the datasource configuration for both the development and production environments. Let’s create a common interface DatasourceConfig that needs to be implemented by both data source implementations:
public interface DatasourceConfig {
    public void setup();
}

Following is the configuration for the development environment:

@Component
@Profile("dev")
public class DevDatasourceConfig implements DatasourceConfig {
    @Override
    public void setup() {
        System.out.println("Setting up datasource for DEV environment. ");
    }
}

And configuration for the production environment:

@Component
@Profile("production")
public class ProductionDatasourceConfig implements DatasourceConfig {
    @Override
    public void setup() {
       System.out.println("Setting up datasource for PRODUCTION environment. ");
    }
}

Now let’s create a test and inject our DatasourceConfig interface; depending on the active profile, Spring will inject DevDatasourceConfig or ProductionDatasourceConfig bean:

public class SpringProfilesWithMavenPropertiesIntegrationTest {
    @Autowired
    DatasourceConfig datasourceConfig;
 
    public void setupDatasource() {
        datasourceConfig.setup();
    }
}

application.properties:

spring.profiles.active=dev

But the most important profiles-related feature that Spring Boot brings is profile-specific properties files. These have to be named in the format applications-{profile}.properties.

In the application-production.properties file, we can set up a MySql data source:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root

Then, we can configure the same properties for the dev profile in the application-dev.properties file, to use an in-memory H2 database:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

10. Difference between @Conditional and @Profile annotations.

  • @Conditional annotation was introduced in Spring 4.0. It is used to develop an “If-Then-Else” type of conditional checking for bean registration.
  • Both Spring @Profiles and @Conditional annotations are used to develop an “If-Then-Else” conditional checking. However, Spring 4 @Conditional is more generalized version of @Profile annotation.
  • Spring 3.1 @Profiles is used to write conditional checking based on Environment variables only. Profiles can be used for loading application configuration based on environments.
  • Spring 4 @Conditional annotation allows Developers to define user-defined strategies for conditional checking. @Conditional can be used for conditional bean registrations.
  • We can use Spring @Conditional annotation for the following scenarios:
    • Condition whether a property is available or not using Environment variables, irrespective of its value.
    • Like Profiles, Condition whether a property value is available or not using Environment variables.
    • Conditions based on a Bean definition are present in Spring Application context.
    • Conditions based on a Bean object are present in Spring Application context.
    • Conditions based on some or all Bean properties values.
    • Conditions based on some Resources are present in current Spring Application Context or not.
    • Conditions based on Bean’s Annotations
    • Conditions Bean’s Method’s Annotations.
    • Conditions based on Bean’s Annotation’s parameter values
    • Conditions based on  Bean’s Method’s Annotation’s parameter values.
  • We can place the annotations in this section on @Configuration classes or @Bean methods.
  • @ConditionalOnClass and @ConditionalOnMissingClass
@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoconfiguration {
    //...
}
  • @ConditionalOnBean and @ConditionalOnMissingBean
@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // ...
}
  • @ConditionalOnProperty
@Bean
@ConditionalOnProperty(
    name = "usemysql", 
    havingValue = "local"
)
DataSource dataSource() {
    // ...
}
  • @ConditionalOnResource
@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
    // ...
}
  • @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
    // ...
}
  • @ConditionalExpression
@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
    // ...
}
  • @Conditional
@Conditional(HibernateCondition.class)
Properties additionalProperties() {
    //...
}

11. @EnableCaching, @Cacheable, @CacheEvict and @CachePut

@EnableCaching

  • It is a class-level annotation. We can enable caching in the Spring Boot application by using the annotation @EnableCaching. It is defined in org.springframework.cache.annotation package. It is used together with @Configuration class.
  • The auto-configuration enables caching and setup a CacheManager, if there is no already defined instance of CacheManager. It scans for a specific provider, and when it does not find, it creates an in-memory cache using concurrent HashMap.
@SpringBootApplication
@EnableCaching
public class SpringBootCachingApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootCachingApplication.class, args);
    }
}

@Cacheable

  • The simplest way to enable caching behavior for a method is to demarcate it with @Cacheable and parameterize it with the name of the cache where the results would be stored:
@Cacheable("addresses")
public String getAddress(Customer customer) {...}
  • The getAddress() call will first check the cache addresses before actually invoking the method and then caching the result.
  • While in most cases, one cache is enough, the Spring framework also supports multiple caches to be passed as parameters:
@Cacheable({"addresses", "directory"})
public String getAddress(Customer customer) {...}
  • In this case, if any of the caches contains the required result, the result is returned and the method is not invoked.

@CacheEvict

  • The problem is size – we don’t want to populate the cache with values that we don’t need often. Caches can grow quite large, quite fast, and we could be holding on to a lot of stale or unused data.
  • The @CacheEvict annotation is used to indicate the removal of one or more/all values – so that fresh values can be loaded into the cache again:
@CacheEvict(value="addresses", allEntries=true)
public String getAddress(Customer customer) {...}
  • Here, we’re using the additional parameter allEntries in conjunction with the cache to be emptied – to clear all the entries in the cache addresses and prepare it for new data.

@CachePut

  • With the @CachePut annotation, you can update the content of the cache without interfering the method execution. That is, the method would always be executed and the result cached.
@CachePut(value="addresses")
public String getAddress(Customer customer) {...}
  • The difference between @Cacheable and @CachePut is that @Cacheable will skip running the method, whereas @CachePut will actually run the method and then put its results in the cache.

12. Spring Boot @ConfigurationProperties example.

https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/

13. How @ComponentScan works in Spring or SpringBoot?

  • If your other package hierarchies are below your main app with the @SpringBootApplication annotation, you’re covered by the implicit Component Scan.
  • If there are beans/components in other packages that are not sub-packages of the main package, you should manually add them as @ComponentScan
  • @SpringBootApplication is defined in the SpringDemo class which is in the package com.codeFactory.example
  • @SpringBootApplication defines an automatic Component Scan on the package com.codeFactory.example.
  • You are fine if all your components are defined in the above package or a sub-package of it.
  • However, let’s say one of the components is defined in package com.codeFactory.test
  • In this case, you would need to add the new package into Component Scan.
  • You have two options:
  • Define @ComponentScan("com.codeFactory")
    • This would scan the entire parent tree of com.codeFactory.
  • Or define two specific Component Scans by using an array.
    • @ComponentScan({"com.codeFactory.example","com.codeFactory.test"})

14. Spring Boot datasource configuration.

https://howtodoinjava.com/spring-boot2/datasource-configuration/

  • A datasource is a factory for connections to any physical data source. An alternative to the DriverManager facility. It uses a URL along with some credentials to establish a database connection.
  • Spring boot allows defining datasource configuration in both ways i.e. Java config and properties config.

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

DataSource Bean

  • Recommended way to create DataSource bean is using DataSourceBuilder class within a class annotated with the @Configuration annotation. The datasource uses the underlying connection pool as well.
@Configuration
public class JpaConfig {
      
    @Bean
    public DataSource getDataSource() 
    {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
        dataSourceBuilder.username("sa");
        dataSourceBuilder.password("");
        return dataSourceBuilder.build();
    }
}

15. Spring Cloud Feign

  • Originally Netflix developed Feign, but as they stopped supporting the library, it is now a community-driven project and is called OpenFeign.
  • When we have Feing dependency on place, we can enable our application to use it. To do that, we have to add @EnableFeignClients annotation to our main application class.
@SpringBootApplication
@EnableFeignClients
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }
}
  • This allows scanning for interfaces that are declared as feign clients.
  • To declare an interface as a feign client, @FeignClient annotation is used. We can see how this looks like on the example of our client interface.
@FeignClient(name = "simple-client", url = "http://localhost:8081")
public interface SimpleClient {

    @GetMapping("/data/{dataId}")
    SimpleClientData getData(@PathVariable int dataId);
}

16. Feign Retryer or error handling using feign Retryer (Synchronous)

  • we can do so by setting application.property, key feign.client.config.[feign client name].retryer
  • If you have more than one retryer logic, you can define for each of your feign client. But if you want to use same retryer for all feign clients, use “default” as key on [feign client name]. Ex:
feign.client.config.default.retryer=com.mypackage.CustomRetryer

17. Error handling using Kafka (Asynchronous) or Dead Letter Topic (DLT)

  • Spring for Apache kafka provides a mechanism to send message to another topic, in case message processes keep failing. This kind of topic is called as Dead Letter Topic (DLT).
  • The message that send to dead letter topic, commonly known as dead letter record.
  • Spring default configuration will send dead letter record from topic “t” into “t.DLT”. appending “DLT” to original topic name.
  • On Java code, we need to configure kafka to retry message processing, and after several failed attempts, publish to dead letter.
  • Create any Config class and define one bean with name deadLetterContainerFactory, which will publish to dead letter topic, after 4 failed retries.
  • To use this dead letter factory, we use in @KafkaListener. Ex: @KafkaListener(topics = "t.test", containerFactory = "deadLetterContainerFactory")
  • To process this message, we have another listener with appending DLT. Ex: @KafkaListener(topics = "t.test.DLT")

18. SpringBoot actuators.

  • Actuator brings production-ready features to our application.
  • Monitoring our app, gathering metrics, understanding traffic, or the state of our database becomes trivial with this dependency.
  • The main benefit of this library is that we can get production-grade tools without having to actually implement these features ourselves.
  • Actuator is mainly used to expose operational information about the running application – health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX beans to enable us to interact with it.
  • Once this dependency is on the classpath several endpoints are available for us out of the box. As with most Spring modules, we can easily configure or extend it in many ways.
  • https://34codefactory.wordpress.com/2019/08/10/spring-boot-actuator-code-factory/
  • https://howtodoinjava.com/spring-boot/actuator-endpoints-example/
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

19. Default available endpoints in actuator

  • By default, only /health and /info are exposed via Web APIs. Rest are exposed via JMX.

20. How to open unavailable / other endpoints in actuator

  • management.endpoints.web.exposure.include=* to expose all endpoints through the Web APIs.

21. Easy way to create connection in Spring Boot

22. Easy way to achieve log in Spring Boot

23. @RepositoryRestResource

Advertisement

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Connecting to %s