SpringBoot Interview Questions

  1. What is Spring Boot?
    – Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications by providing a convention-over-configuration approach.
    Spring Boot is a powerful framework designed to simplify the bootstrapping and development of Spring applications. Here are some of its most notable features:

    1. Auto-Configuration: Spring Boot can automatically provide configuration for application functionality common to many Spring applications based on the libraries on the classpath.
    2. Standalone: Spring Boot applications are stand-alone and web servers can be embedded in the application. This makes it easy to deploy and run Spring Boot applications without needing an external server.
    3. Production Ready: Spring Boot has built-in features like health checks and metrics, which makes it easy to monitor and manage production applications.
    4. No Code Generation: Spring Boot does not generate code and there is absolutely zero requirement for XML configuration.
    5. Opinionated Defaults: Spring Boot gives you a set of default settings, libraries, and configurations so you can get started quickly without needing to figure out what’s the best way to set up a Spring application.
    6. Spring Boot Initializr: A web-based tool that allows users to easily bootstrap a new Spring Boot application, generating a basic project structure, Maven/Gradle build files, and application properties.
    7. Embedded Web Server Support: Provides options to have embedded Tomcat, Jetty, or Undertow servers, eliminating the need for external server setups.
    8. Spring Boot Actuator: Provides production-ready features such as monitoring, metrics, auditing, and more.
    9. Spring Boot CLI: This command-line tool can be used to run and test Spring Boot applications from a console.
    10. Flexible Configuration: Spring Boot allows developers to configure their application using a properties file, YAML, environment variables, or command-line arguments.
    11. Profiles: Enables the separation of parts of the configuration and makes it available only in certain environments, thus allowing for different configuration setups (e.g., dev, test, prod).
    12. Logging: Provides pre-configured logging via SLF4J and Logback. Developers can also easily switch to other logging solutions if needed.
    13. Integrated Data Access: Simplified database access and connection pooling with support for a wide range of relational and NoSQL databases.
    14. Developer Tools: Features like automatic restart of the application upon file changes and browser live-reload capabilities speed up the development process.
    15. Security: Integration of Spring Security makes it easier to secure web applications and RESTful services.
    16. Externalized Configuration: Spring Boot provides the ability to externalize and manage application configurations for different environments without modifying the application’s binary.
    17. Admin Features: Web-based or shell-based admin features for managing and monitoring Spring Boot applications.
    18. Web Application: Simplified Spring MVC setup with view templates, static web resources, form bindings, and more.
    19. Extensibility: Spring Boot provides a lot of extensions for building services and other types of web modules.
    20. Cloud Ready: Easy integration with Spring Cloud, making it a great choice for building microservices and cloud-native applications.
  2. What are the benefits of using Spring Boot?
    – Spring Boot makes it easy to create stand-alone, production-grade Spring applications.
    – Spring Boot provides a number of features that make it easier to develop, test, and deploy Spring applications.
    – Spring Boot is based on the principle of “convention over configuration,” which means that it provides default configurations and settings that can be overridden as needed.
    – Spring Boot has a large community of users and developers, which means that there is a lot of support available.
  3. What are the Spring Boot key components?
    • The Spring Boot starter dependencies are a set of Maven dependencies that provide the basic functionality for a Spring Boot application.
    • The Spring Boot Actuator is a set of endpoints that provide management and monitoring information about a Spring Boot application.
    • The Spring Boot CLI is a command-line tool that can be used to create, run, and manage Spring Boot applications.
    • The Spring Boot documentation is a comprehensive resource that provides information on all aspects of Spring Boot.
  4. Why Spring Boot over Spring?
    • Spring Boot is a more lightweight framework than Spring, which makes it easier to learn and use.
    • Spring Boot provides a number of features that make it easier to develop, test, and deploy Spring applications.
    • Spring Boot is based on the principle of “convention over configuration,” which makes it easier to configure Spring applications.
    • Spring Boot has a large community of users and developers, which means that there is a lot of support available.
  5. What are the basic annotations that Spring Boot offers?
    • The @SpringBootApplication annotation is the main annotation that is used to configure a Spring Boot application.
    • The @Component annotation is used to mark a class as a Spring component.
    • The @Configuration annotation is used to mark a class as a Spring configuration class.
    • The @Bean annotation is used to declare a bean in a Spring application.
    • The @Autowired annotation is used to inject dependencies into a Spring bean.
  6. What is Spring Boot dependency management?
    • Spring Boot dependency management is a feature that allows you to declare the dependencies that your Spring Boot application needs in the pom.xml file.
    • Spring Boot dependency management will automatically download and install the dependencies that your application needs.
    • Spring Boot dependency management also provides a number of features that make it easier to manage dependencies, such as version management and dependency conflict resolution.
  7. Explain what dependency injection is in springboot.
    Dependency Injection (DI) is one of the core principles upon which the Spring Framework is built. It is a design pattern that facilitates the inversion of control, which means that objects are given their dependencies rather than creating them internally. This results in a decoupled, modular, and more testable codebase.

    Explanation:

    In a standard application without dependency injection, components and services often create or look up their dependencies. This creates tight coupling between components and makes them harder to test or reuse. With DI, components declare their dependencies (typically via constructor arguments, properties, or annotations), and a container or framework (like Spring) provides those dependencies. This helps in:

    1. Decoupling: Components are not responsible for finding or creating their dependencies.
    2. Flexibility: Dependencies can be easily swapped or mocked for testing.
    3. Configuration Management: Configuration can be centralized, and objects can be wired up with different configurations for different scenarios.
    4. Life Cycle Management: The framework/container can manage the entire life cycle of beans including their creation, initialization, destruction, and more.

      Spring Boot Dependency Injection Examples:

      1. Constructor-based Injection: Here, dependencies are provided through a class constructor.
        @Service
        public class OrderService {
            private final UserRepository userRepository;
        
            @Autowired
            public OrderService(UserRepository userRepository) {
                this.userRepository = userRepository;
            }
        
            // Other methods
        }
        

        Note: In modern Spring versions, if a class has a single constructor, the @Autowired annotation can be omitted, and Spring will use that constructor by default.

      2. Setter-based Injection: Dependencies are provided through setters.
        @Service
        public class OrderService {
            private UserRepository userRepository;
        
            @Autowired
            public void setUserRepository(UserRepository userRepository) {
                this.userRepository = userRepository;
            }
        
            // Other methods
        }
        
      3. Field-based Injection: Directly injecting into fields without setters. This approach is less recommended as it makes the code harder to unit-test without a Spring context.
        @Service
        public class OrderService {
            @Autowired
            private UserRepository userRepository;
        
            // Other methods
        }
        
      4. Qualifier Annotation: When there are multiple beans of the same type and you need to specify which bean to wire, you can use the @Qualifier annotation.
        @Service
        public class OrderService {
            private final DataSource dataSource;
        
            @Autowired
            public OrderService(@Qualifier("mainDataSource") DataSource dataSource) {
                this.dataSource = dataSource;
            }
        
            // Other methods
        }
        
  8. Explain to me the problem IOC is solving.
    Inversion of Control (IoC) is a design principle that addresses the challenges of creating more modular, flexible, and testable software. Before diving into the solution IoC provides, let’s first understand the problem it aims to solve.

    The Problem:

    1. Tight Coupling: In traditional application development, objects often create or find their dependencies directly. This tight coupling makes the components hard to reuse, test, and maintain.Example: Imagine a car (Car) object that creates its own engine (Engine) instance.
      public class Engine {
          public void start() {
              // Start engine
          }
      }
      
      public class Car {
          private Engine engine;
      
          public Car() {
              this.engine = new Engine();
          }
      }
      

      In the example above, the Car class is tightly coupled to a specific Engine. This makes it challenging to replace Engine with a different implementation or to mock the engine during testing.

    2.  Configuration Sprawl: When instantiating and configuring objects directly within other objects, configuration details can be scattered throughout the application. This can lead to duplication and make the system harder to evolve.
    3. Lifecycle Management: Objects might have specific lifecycles. Manually managing these lifecycles can become cumbersome, especially in large applications.

    How IoC Solves the Problem:

    1. Decoupling through Dependency Injection: Rather than objects creating their own dependencies, they receive them from an external source (like an IoC container). This is known as Dependency Injection (DI), a form of IoC.Example:
      public class Car {
          private Engine engine;
      
          public Car(Engine engine) {
              this.engine = engine;
          }
      }
      

       

      Here, the Car doesn’t create its Engine. Instead, it’s supplied with an engine. This makes it possible to provide different engine implementations or mock engines for testing.

    2. Centralized Configuration: IoC allows configuration details to be centralized (e.g., in XML files, annotations, or Java configurations). This centralization reduces duplication and provides a single point of truth.Example using Spring:
      <!-- Spring XML Configuration -->
      <bean id="engine" class="com.example.Engine" />
      
      <bean id="car" class="com.example.Car">
          <constructor-arg ref="engine"/>
      </bean>
      

       

    3. Managed Lifecycle: An IoC container can manage the lifecycle of objects, from instantiation to destruction. This includes handling singleton/shared instances, initializing beans, and cleaning up resources.Example: With Spring, you can have the IoC container call lifecycle methods:
      @Component
      public class Engine {
          
          @PostConstruct
          public void initialize() {
              // Initialization code
          }
      
          @PreDestroy
          public void cleanup() {
              // Cleanup code
          }
      }
      

      In essence, IoC flips the traditional flow of control. Instead of objects controlling their own dependencies, a container or framework takes on the responsibility. This inversion leads to software that’s more modular, easier to test, and more resilient to change.

      Here, the initialize method is called after the Engine bean is created, and cleanup is called before it’s destroyed.

  9. Explain what IOC containers are in Java Spring Boot.
    Inversion of Control (IoC) is a principle where the control flow of a program is inverted: instead of the application code controlling the flow, the external framework or container does. In the context of the Spring Framework, the IoC container is responsible for instantiating, configuring, and assembling objects (known as beans in Spring terminology).

    Explanation:

    The IoC container receives metadata from XML files, annotations, or Java configuration classes, and then uses this metadata to create and manage the lifecycle of the beans. The main tasks of the IoC container are:

    1. Instantiating the Bean: Creating an object from its definition.
    2. Wiring the Beans: Connecting beans together, which means setting properties and injecting dependencies.
    3. Managing the Bean’s Lifecycle: Calling initialization and destruction methods where they’re defined.
    4. Configuring the Beans: Applying aspects, proxies, and other post-processing features.

    There are two primary types of IoC containers in Spring:

    1. BeanFactory: This is the basic container, providing fundamental support for DI. It’s lightweight and meant for simple use-cases.
    2. ApplicationContext: This is a more advanced container, built on top of BeanFactory. It provides additional features such as event propagation, declarative mechanisms to create a bean, integration with AOP (Aspect-Oriented Programming), and more. In most Spring-based applications (including Spring Boot apps), ApplicationContext is used more often than BeanFactory.

    Spring Boot and IoC Container:

    Spring Boot simplifies the use of the IoC container by eliminating most of the boilerplate configuration. With features like auto-configuration and component scanning, Spring Boot makes it easier to create, wire, and manage beans with minimal explicit configuration.

    Examples:

    1. Creating a Bean using Annotations:
      @Component
      public class HelloWorld {
          public String sayHello() {
              return "Hello, World!";
          }
      }
      
    2. Injecting a Dependency using Autowiring:
      @Service
      public class MessageService {
          private final HelloWorld helloWorld;
      
          @Autowired
          public MessageService(HelloWorld helloWorld) {
              this.helloWorld = helloWorld;
          }
      
          public void showMessage() {
              System.out.println(helloWorld.sayHello());
          }
      }
      
    3. Using ApplicationContext in a Spring Boot Application:
      @SpringBootApplication
      public class MyApp {
          public static void main(String[] args) {
              ApplicationContext context = SpringApplication.run(MyApp.class, args);
              MessageService messageService = context.getBean(MessageService.class);
              messageService.showMessage();
          }
      }
      
  10. Can we create a non-web application in Spring Boot?
    • Yes, you can create a non-web application in Spring Boot.
    • To do this, you need to exclude the web dependency from the pom.xml file.
    • You can also use the @SpringBootApplication annotation with the annotation attribute set to ‘false’.
  11. Is it possible to change the port of the embedded Tomcat server in Spring Boot?
    • Yes, it is possible to change the port of the embedded Tomcat server in Spring Boot.
    • To do this, you need to set the server.port property in the application.properties file.
    • For example, to set the port to 8081, you would set the server.port property to 8081.
  12. What is the default port of tomcat in spring boot?
    • The default port of tomcat in spring boot is 8080.
    • This means that if you do not specify a port in the application.properties file, the embedded Tomcat server will listen on port 8080.
  13. What are the different ways to configure Spring Boot?
    • There are three main ways to configure Spring Boot:
      • Using the application.properties file
      • Using the @Configuration class
      • Using the Spring Boot CLI
  14. What are the different ways to run a Spring Boot application?
    • There are three main ways to run a Spring Boot application:
      • Running the application as a Java application
      • Running the application as a Spring Boot JAR file
      • Running the application as a Docker container
  15. What are the different ways to test a Spring Boot application?
    • There are three main ways to test a Spring Boot application:
      • Unit testing
      • Integration testing
      • End-to-end testing
  16. How is Spring Boot different from Spring MVC?
    Spring Boot is a framework built on top of Spring to simplify its setup and usage, whereas Spring MVC is a web framework in the Spring ecosystem.
  17. What are Spring Boot starters?
    Starters are templates that contain a collection of all the relevant transitive dependencies a user needs to start a specific kind of project.
  18. What’s the advantage of Spring Boot’s “Opinionated Defaults”?
    They reduce the developer’s effort in decision-making and configuration.
  19. Explain Spring Boot’s @SpringBootApplication annotation?
    It’s a combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  20. How do you customize Spring Boot’s banner?
    By creating a banner.txt file in the src/main/resources directory or setting a banner.location property.
  21. How does Spring Boot handle properties/env variables?
    Using @Value annotation or by injecting the Environment object.
    Spring Boot provides a comprehensive and flexible way to handle properties. The framework offers several layers of property sources and conventions that make configuration easy and intuitive. Here’s a detailed breakdown of how Spring Boot handles properties:

    1. Externalized Configuration: Spring Boot allows you to externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments, among others, to externalize configuration.
    2. application.properties and application.yml:
      • Spring Boot looks for these files at the root of the classpath (like in src/main/resources).
      • These files can be used to define default properties.
    3. Profile-specific Properties:
      • Spring Boot lets you define properties specific to a profile (e.g., application-dev.properties for a dev profile).
      • These properties are only activated when the corresponding profile is active.
    4. Property Precedence:
      • Properties defined can be overridden. For instance, properties passed as command-line arguments override those defined in application.properties
      • Spring Boot has a specific order in which it considers property values, ranging from command-line arguments (highest precedence) to application.properties or application.yml in the jar (lowest precedence).
    5. Environment Properties:
      • Environment variables can also be used as properties. For example, a variable named SPRING_DATASOURCE_URL would map to the spring.datasource.url property in the application.
    6. Using the @Value Annotation:
      • You can bind properties directly to fields in your beans using the @Value("${property.name}") annotation.
        @Value("${custom.property}") 
        private String customProperty;
    7. Type-safe Configuration (Configuration Properties):
      • Instead of using the @Value annotation, you can bind properties to POJOs annotated with @ConfigurationProperties. This method is type-safe and offers additional benefits like validation and code-completion in IDEs.
        @ConfigurationProperties(prefix="custom")
        public class CustomProperties {
            private String property;
            // getters and setters
        }
        
    8. Placeholder Resolution:
      • Spring Boot can replace placeholders in properties and other parts of your configuration (e.g., ${another.property}).
    9. Relaxed Binding:
      • Spring Boot uses a “relaxed” strategy for binding property names, so spring.datasource.url, spring.datasource-url, SPRING_DATASOURCE_URL, and spring.datasource_url would all match the spring.datasource.url property.
  22. What is YAML? How is it related to Spring Boot?
    YAML is a human-readable data format. Spring Boot supports YAML for property configuration.
  23. Describe Profiles in Spring Boot.
    In Spring Boot, profiles provide a way to segregate parts of your application’s configuration and make it available only in certain environments. It’s a core feature of the Spring framework that has been deeply integrated into Spring Boot, allowing developers to easily manage environment-specific properties and beans.Here’s a detailed description of profiles in Spring Boot:

    1. Purpose:
      • Profiles are used when you want to apply specific configuration settings only in a specific environment. For instance, you might have different data sources for development and production or you might want to enable certain features only in the development environment.
    2. Activation:
      • Profiles can be activated in various ways:
        • Through the spring.profiles.active property (e.g., in application.properties or as a command-line argument).
        • Setting the SPRING_PROFILES_ACTIVE environment variable.
        • Using the SpringApplication.setAdditionalProfiles(...) method programmatically.
    3. Profile-specific Configuration Files:
      • You can define properties specific to a profile in separate configuration files. For example, application-dev.properties will only be applied when the dev profile is active.
      • Similarly, for YAML files, you could use application-dev.yml.
    4. Defining Beans Conditionally:
      • You can define Spring beans that are conditionally created based on which profiles are active using the @Profile annotation:
        @Profile("dev")
        @Bean
        public DataSource dataSource() {
            return new EmbeddedDatabaseBuilder().build();
        }
        
    5. Multiple Profiles:
      • Multiple profiles can be active at once. This allows you to compose configurations from multiple sources.
      • For example, you might have a cloud profile that’s used for any cloud provider and a aws profile that’s specific to AWS. You can activate both profiles simultaneously.
    6. Default Profiles:
      • If no profiles are explicitly activated, the default profile will be used.
      • This can be useful to apply certain configurations when no other profiles are active.
    7. Profile-specific Logging:
      • Log configurations can be profile-specific as well. For instance, you might want more detailed logging in a development environment compared to production.
    8. Negating Profiles:
      • You can define beans that are created when a profile is not active using the “!” notation:
        @Profile("!prod")
        @Bean
        public DataSource dataSource() {
            // This bean will be created when the 'prod' profile is NOT active
        }
        
    9. Application Arguments:
      • Profiles can be activated via command-line arguments when running the Spring Boot application. For instance:
        java -jar myapp.jar --spring.profiles.active=prod
        
  24. How do you activate a Spring profile?
    Using spring.profiles.active property.
  25. What is Spring Boot Actuator?
    It provides production-ready features to monitor and manage a Spring Boot application.
  26. Mention a few Actuator endpoints.
    /health, /info, /metrics, /env.
  27. How does Spring Boot handle database migrations?
    Using tools like Flyway or Liquibase.
  28. What’s the use of @EntityScan?
    It’s used to specify the base packages where JPA will scan for entities.
  29. How can you run a Spring Boot application?
    Using the SpringApplication.run() method.
  30. How can you customize Spring Boot’s embedded servers?
    By modifying server.* properties (e.g., server.port).
  31. Describe Spring Boot’s Data JPA starter.
    It provides key dependencies for Hibernate, Spring Data, and JPA.
  32. What’s the use of @RepositoryRestResource?
    It exposes JPA entities directly as REST endpoints.
  33. How does Spring Boot handle AOP?
    By using Spring AOP and spring-boot-starter-aop.
  34. What are Spring Boot’s initializers?
    They provide a web-based UI to generate Spring Boot projects.
  35. How can you override default properties in Spring Boot?
    By specifying them in application.properties or application.yml.
  36. How does Spring Boot support microservices?
    With Spring Cloud, which provides tools to build microservice architectures.
  37. Explain Spring Boot’s @RestController vs @Controller.
    @RestController is a shorthand for @Controller + @ResponseBody.
  38. How to enable transaction management in Spring Boot?
    With @EnableTransactionManagement and by using @Transactional on methods.
  39. How to handle exceptions in Spring Boot?
    Using @ControllerAdvice and @ExceptionHandler.
  40. Explain the Spring Boot testing support.
    It supports JUnit and provides spring-boot-starter-test with utilities like MockMvc.
  41. How can you produce a standalone Java application using Spring Boot?
    By packaging the app as a jar with embedded Tomcat, Jetty, or Undertow.
  42. What are Spring Boot build plugins?
    They help in packaging executable jars/wars, e.g., spring-boot-maven-plugin.
  43. How to exclude a particular package from Component Scan?
    With @ComponentScan(excludeFilters = @Filter).
  44. How can you modify the default location of application.properties?
    Using spring.config.location property.
  45. Explain embedded servers in Spring Boot.
    Spring Boot supports Tomcat, Jetty, and Undertow as embedded servers, which means applications can run as standalone apps.
  46. How can you change the default port in Spring Boot?
    By setting server.port in application.properties.
  47. Describe Spring Boot’s @Conditional
    It indicates a component is only eligible for registration when a specific condition matches.
  48. What is the use of @SpringBootTest?
  • It signals that the context should be a SpringApplication and loads all registered beans.
  • @SpringBootTest is an annotation provided by Spring Boot that is used for integration testing. It helps to bootstrap the entire container (depending on the provided configuration), so you can test the application in scenarios close to the actual use.Features of @SpringBootTest:
    1. Autoconfigure Spring Boot Application: It automatically configures your application based on the provided configuration and starts the application context.
    2. Web Environment: You can specify the type of web environment to use (e.g., MOCK, RANDOM_PORT, DEFINED_PORT, or NONE).
    3. Properties: You can define or override properties for the test environment.

    Examples of using @SpringBootTest:

    1. Basic Usage:
      @SpringBootTest
      class MyApplicationTests {
      
          @Test
          void contextLoads() {
          }
      }
      

      This test ensures that the application context loads without any issues.

    2. Using a Random Port: If your application starts a web server, you can start it on a random port to avoid port conflicts during testing:
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
      class MyWebApplicationTests {
          
          @Autowired
          TestRestTemplate restTemplate;
      
          @Test
          void testHomeEndpoint() {
              String response = restTemplate.getForObject("/", String.class);
              assertEquals("Hello World", response);
          }
      }
      
    3. Using a Mock Web Environment: For web applications, you may want to avoid starting a server altogether and just use the mock servlet environment:
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
      class MyWebMockTest {
      
          @Autowired
          MockMvc mockMvc;
      
          @Test
          void testEndpoint() throws Exception {
              mockMvc.perform(MockMvcRequestBuilders.get("/"))
                     .andExpect(status().isOk())
                     .andExpect(content().string("Hello World"));
          }
      }
      
    4. Overriding Properties: You can override properties for specific test scenarios:
      @SpringBootTest(properties = {"custom.property=value"})
      class PropertyOverrideTest {
          //...
      }
      
    5. Using with @ActiveProfiles: To activate certain profiles during testing, you can combine it with @ActiveProfiles:
      @SpringBootTest
      @ActiveProfiles("test")
      class MyProfileTest {
          //...
      }
      

      The @SpringBootTest annotation simplifies integration testing for Spring Boot applications by setting up and tearing down the application context and providing various utilities and configurations specific to the testing phase.

35. How can you serve static content in Spring Boot?

  • By placing it in the /public, /resources, /static, or /META-INF/resources directories.
    In Spring Boot, serving static content is straightforward and requires minimal configuration due to its opinionated defaults. Here’s how you can serve static content in a Spring Boot application:

    1. Default Static Content Locations:

    By default, Spring Boot serves static content from the following locations inside your project:

    • /META-INF/resources/
    • /resources/
    • /static/
    • /public/

    For instance, if you place an index.html file inside the src/main/resources/static/ directory of your Spring Boot application, you can access it by visiting http://localhost:8080/index.html after starting your application.

    2. Custom Static Content Locations:

    If you want to customize the static content locations, you can do so by configuring the spring.resources.static-locations property. For example, to serve static content from a custom-dir directory:

    spring.resources.static-locations=classpath:/custom-dir/
    

     

36. Describe the hierarchy of application.properties in Spring Boot.

  • @TestPropertySource, @SpringBootTest.properties, and inside the JAR are examples of levels.

    In Spring Boot, the application.properties (or its YAML counterpart, application.yml) file is the primary means for configuring application settings. Spring Boot provides a flexible system of looking for this configuration file in various locations and offers a hierarchy that determines the order of precedence for reading these configurations.

    Here’s the hierarchy for application.properties locations, starting from the highest precedence:

    1. Command Line Parameters:
      • Properties passed as command-line arguments, e.g., java -jar app.jar --server.port=8081
    2. Properties from SPRING_APPLICATION_JSON:
      • Properties can be passed as a JSON string via the SPRING_APPLICATION_JSON environment variable.
    3. Java System Properties:
      • Properties set using -D argument, e.g., java -Dserver.port=8081 -jar app.jar
    4. OS Environment Variables:
      • Operating System specific environment variables. For example, a property named server.port can be sourced from an environment variable named SERVER_PORT.
    5. Configuration files outside the packaged jar:
      • A application.properties or application.yml located in the same directory from which the application is run.
      • Or in a ./config sub-directory of the directory from which the application is run.
    6. Configuration files inside the packaged jar:
      • A application.properties or application.yml at the root of the classpath, typically inside the src/main/resources directory.
      • Or in a /config package or directory inside the jar.
    7. Configuration properties on the classpath:
      • A application.properties or application.yml located in the classpath root.
    8. Default properties:
      • Properties set using SpringApplication.setDefaultProperties.

    Profile-specific properties:

    Along with the above, Spring Boot allows for profile-specific property files. These are named like application-{profile}.properties or application-{profile}.yml. Profile-specific property files have precedence over the default application.properties or application.yml but are ordered by the same precedence rules mentioned above.

    For example, if a dev profile is active, application-dev.properties outside the jar will override the application.properties outside the jar, but both will be overridden by any value passed as a command-line argument.

    Conclusion: The hierarchy and the ability to source configurations from various locations allow for a high degree of flexibility. You can have default settings packaged within your application and override them for different environments using external files or even command-line arguments. This makes it easier to manage configurations across different deployment scenarios without changing the packaged application.

37. What is a Spring Boot Fat JAR?

  • A JAR that contains embedded dependencies, including the server.

38. What are the main advantages of using Spring Boot?

  • Rapid development, production-ready setups, convention over configuration, and no code generation.

39. How do you enable debug logging in Spring Boot?

  • Set logging.level.root=DEBUG in application.properties.

40. Explain the importance of the pom.xml file in Spring Boot.

  • It defines project metadata, dependencies, and build plugins for Maven-based projects.

41. What’s the purpose of @EnableAutoConfiguration?

  • It enables automatic configuration based on libraries present in the classpath.

42. How does Spring Boot simplify database connectivity?

  • With auto-configured data sources and spring-boot-starter-data-jpa.
    Spring Boot significantly simplifies database connectivity by providing a number of automated configurations, sensible defaults, and integration with popular Java database tools and libraries. Here’s how Spring Boot aids in easing database connectivity:

    1. Auto-configuration:
      • When you add a database-related dependency (like an embedded database or a JPA implementation), Spring Boot attempts to set up a database connection based on the libraries present in the classpath.
    2. Data Source Configuration:
      • Spring Boot can provide a lot of database configuration automatically, based on the properties defined in the application.properties or application.yml files.
      • For instance, just by defining properties like spring.datasource.url, spring.datasource.username, and spring.datasource.password, you can configure a data source without any manual bean definitions.
        spring.datasource.url=jdbc:mysql://localhost:3306/mydb
        spring.datasource.username=root
        spring.datasource.password=secret
    3. Embedded Databases:
      • Spring Boot provides out-of-the-box support for H2, HSQL, and Derby embedded databases. When any of these is on the classpath, Spring Boot automatically sets up an embedded database for you.
    4. Connection Pooling:
      • Connection pooling libraries like HikariCP, Tomcat, and DBCP2 are automatically configured when they’re on the classpath.
      • By default, if HikariCP is on the classpath, it’s chosen as the primary connection pool due to its performance and concurrency benefits.
        spring.datasource.hikari.maximum-pool-size=10
    5. JPA & Spring Data JPA:
      • By including the Spring Data JPA starter, Spring Boot auto-configures Hibernate as the default JPA provider.
      • With minimal properties set, Spring Boot sets up Hibernate, scans entities, and sets up a default EntityManager.
    6. Repository Support:
      • With Spring Data JPA, you can create interfaces extending CrudRepository or JpaRepository and Spring Boot automatically provides the implementation at runtime, enabling CRUD operations on entities without writing the boilerplate code.
    7. Database Initialization:
      • Spring Boot can auto-detect SQL scripts (like schema.sql and data.sql) and run them at startup to initialize the database.
      • It also supports using tools like Flyway or Liquibase for database version control and migration by simply including their dependencies and configuration.
      • Description: Spring Boot can automatically run SQL scripts on startup for database initialization.
      • Example: If you place a file named schema.sql in the src/main/resources directory, Spring Boot will execute it on startup.schema.sql:
    8. Profile-based Configuration:
      • Different application-{profile}.properties files can be used for different environments. This means you can have separate configurations for development, staging, and production, making it easy to switch between databases based on the active profile.
    9. JDBC Template:
      • If you’re using plain JDBC, Spring Boot provides auto-configuration for the JdbcTemplate, making it easier to interact with relational databases without managing connections and exceptions manually.
        @Autowired
        JdbcTemplate jdbcTemplate;
        
        public int getCountOfBooks() {
            return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM book", Integer.class);
        }
        
    10. Metrics & Health Indicators:
      • When used with Spring Boot Actuator, it provides metrics and health checks related to database connectivity, helping in monitoring and managing the application in production environments.
    11. Exception Translation:
      • Spring Boot integrates the persistence exception translation mechanism of Spring, which translates lower-level SQL and database exceptions into Spring’s DataAccessException, making it easier to handle database-related errors in a consistent way.In essence, Spring Boot removes much of the boilerplate code traditionally associated with setting up and managing database connections in a Spring application. This allows developers to focus on their domain logic rather than the intricacies of database setup and connectivity.

43. What is the importance of @Repository in Spring Boot?

  • Marks the class as a DAO, throws specific exceptions, and can be scanned by Spring.

44. How can you specify the active profile while running a Spring Boot application?

  • Using --spring.profiles.active=myprofile during startup.

45. How can you secure a Spring Boot application?

  • With spring-boot-starter-security and @EnableWebSecurity.
    Securing a Spring Boot application is made simpler with the integration of Spring Security. Spring Security provides a comprehensive security solution for Java applications, handling authentication, authorization, and other security concerns. Here’s how you can secure a Spring Boot application, along with illustrative examples:

    1. Add Spring Security Dependency:

    First and foremost, you’ll need to add the Spring Security starter to your pom.xml (if using Maven):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  • Basic Authentication:

    By merely including the above dependency, Spring Boot will set up basic authentication for all routes with a default user named “user” and a generated password that’s displayed in the console on startup.

    Example: Accessing any endpoint without authentication will return a 401 Unauthorized. Use the provided username and password in the request header or when prompted by the browser to authenticate.

    3. Configure Custom User Details:

    You can configure user details and their roles in memory or retrieve them from a database.

    Example – In-memory Authentication:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("admin").password("{noop}admin123").roles("ADMIN")
                .and()
                .withUser("user").password("{noop}user123").roles("USER");
        }
    }
    

    Authorize Requests:

    You can specify which routes or endpoints are accessible by which roles.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
            .antMatchers("/").permitAll()
            .and().formLogin();
    }
    

     

     

46. What is a CommandLineRunner in Spring Boot?

  • It lets you run specific code once the application context is fully started.

47. Describe the structure of a typical Spring Boot project.

  • It follows the Maven/Gradle directory structure, with main application code in src/main/java and resources in src/main/resources.

48. How can you customize the Jackson ObjectMapper in Spring Boot?

  • By defining a @Bean of type ObjectMapper in a configuration class.

49. What are the benefits of using the Spring Boot DevTools?

  • Automatic restart, live reload, and developer-friendly properties.

50. What is spring-boot-starter-parent?

  • It’s a parent POM providing dependency and plugin management for Spring Boot applications.



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

required
required


Leave a Reply

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