Profile Photo

Spring boot interview question

Created on: Sep 30, 2024

  1. What is a web server ? A web server is a software system that hosts websites and delivers web content to users over the Internet.

  2. What is Apache Tomcat server. Apache Tomcat is a popular open-source web server and Java servlet container. It's primarily used to serve Java web applications. A Java Servlet Container, also known as a Servlet Engine, is a part of a web server that interacts with Java Servlets. It is responsible for managing the lifecycle of servlets, processing requests, and generating responses. Java Servlet is a server-side component that handles client requests, processes them, and generates dynamic web content, usually in the form of HTML, XML, or JSON. Servlets are a fundamental part of Java EE (Enterprise Edition) technology and are commonly used in web applications to provide business logic and manage user interactions.

  3. How to get different scope of beans in spring boot application.

    @Scope("prototype"), @Scope("singleton")

    Other Scope are:

    1. request
    2. session
    3. application
    4. WebSocket
  4. When to not use spring boot application ?

    1. Resource-Constrained Environments: If your application needs to run on devices with severely constrained memory
    2. High-Performance, Low-Latency Requirements: For applications with strict real-time requirements custom solution is better.
    3. Migrating a large, heavily configured legacy project to Spring Boot can be challenging
  5. What is the difference between Singleton scope in spring and Singleton design pattern ?

    • Scope vs. Pattern: Spring's Singleton scope is a management mechanism, while the Singleton design pattern is a way to control object creation.
    • Implementation: Spring handles Singleton scope, while the developer implements the Singleton pattern.
    • Context: Spring Singleton is per Application Context, while the Singleton pattern is typically per ClassLoader.
    • Flexibility: Spring provides other scopes (prototype, request, session, etc.), while the Singleton pattern is more rigid.
  6. Give me sample example how Transaction works using AOP in spring boot ?

    • When you annotate a method with @Transactional, Spring creates a proxy object for the class using Java Reflection API or CGLIB (bytecode generation tools)
    • The proxy intercepts calls to the annotated method and wraps them with transaction logic.
  7. How to initialize bean only if a condition matches in spring boot

    1. Using @Conditional annotation
    import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; class MyCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String conditionProperty = context.getEnvironment().getProperty("my.condition.property"); return "true".equalsIgnoreCase(conditionProperty); } } @Configuration public class MyConfig { @Bean @Conditional(MyCondition.class) public MyService myService() { return new MyService(); } }
    1. Using @ConditionalOnProperty
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfig { @Bean @ConditionalOnProperty(name = "my.condition.property", havingValue = "true", matchIfMissing = false) public MyService myService() { return new MyService(); } }
    1. Using profile
    import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class MyConfig { @Bean @Profile("dev") public MyService myServiceForDev() { return new MyService(); } @Bean @Profile("prod") public MyService myServiceForProd() { return new MyService(); } }
    1. @ConditionalOnExpression
    import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfig { @Bean @ConditionalOnExpression("'${my.condition.property}' == 'true'") public MyService myService() { return new MyService(); } }

    ref geeksforgeeks

  8. Difference between Spring Data JPA and Hibernate ?

    FeatureHibernateSpring Data JPA
    Level of AbstractionLower-levelHigher-level
    Boilerplate CodeMoreLess
    Query MechanismsJPQL, SQL, Criteria APIMethod-based queries, JPQL, SQL
    Integration with SpringIntegrates wellTightly integrated with Spring ecosystem

    Important Points:

    1. By default Spring uses Hibernate as the default JPA vendor.
    2. JPA is not an implementation. It is only a Java specification.Hibernate is an implementation of JPA.
    3. Other implementation of JPA are EclipseLink, OpenJPA
  9. What are the various annotation used in Spring, spring boot application and JPA application ?

    1. @GeneratedValue: Specifies how the primary key value should be generated
      1. @GeneratedValue -> @GeneratedValue(strategy = GenerationType.IDENTITY). primary key value is generated by the database itself, typically using an auto-increment column
      2. Auto - Lets JPA decide the strategy based on the database.
      3. Sequence - Uses a database sequence object to generate unique values
      4. UUID ->
      5. TABLE - Uses a separate database table to generate unique values.
    2. @Entity annotation marks this class as a JPA entity
    3. @Table annotation specifies the name of the database table to map to
    4. @Id annotation marks the id field as the primary key of the table
  10. What is dependency Injection and IOC in spring boot.

  11. DIfference between Spring and spring boot.

  12. Difference between

  13. What is difference between @Controller and @Service vs @Repository.

  14. Some jpa lavel annotation

    • @Entity: Marks a Java class as a JPA entity, which can be persisted to a database.
    • @Table: Specifies the name of the database table to map the entity to.
    • @Id: Specifies the primary key field of the entity.
    • @GeneratedValue: Specifies how the primary key value should be generated.
    • @Column: Specifies the mapping of the entity field to a database column.
    • @JoinColumn: Specifies the mapping of a foreign key column between two entities.
    • @OneToOne: Defines a one-to-one relationship between two entities.
    • @OneToMany: Defines a one-to-many relationship between two entities.
    • @ManyToOne: Defines a many-to-one relationship between two entities.
    • @ManyToMany: Defines a many-to-many relationship between two entities.
    • @NamedQuery: Defines a named query for an entity.
    • @NamedQueries: Defines a set of named queries for an entity.
    • @Transient: Specifies that an entity field should not be persisted to the database.
    • @Version: Specifies the version field of the entity, used for optimistic locking.
    • @Temporal: Specifies the temporal type of a date or timestamp entity field.
    • @Repository: Marks the interface as a Spring Data JPA repository.
    • @Query: Defines a custom JPQL or native SQL query for an entity.
    • @NamedQuery: Defines a named query for an entity.
    • @Param: Binds a method parameter to a named parameter in a custom query.
    • @Lock: Specifies the lock mode to use when fetching an entity.
    • @EntityGraph: Specifies the entity graph to use when fetching an entity.
    • @Procedure: Specifies the name of a stored procedure to call.
    • @ProcedureParameter: Specifies a parameter for a stored procedure.
    • @EnableJpaRepositories: Enables Spring Data JPA repositories in a Spring Boot application.
    • @Transactional: Specifies that a method should be executed within a transaction.
  15. What are the types of beans and how to create them in spring boot.

    1. SIngleton
    2. Prototype
  16. What are the difference between spring vs spring boot ?

    1. Spring boot includes embedded tomcat server or jetty while spring relies on external webserver like tomcat.
    2. Spring boot uses spring boot starter guarantees consistent and compatable version of dependency. In spring it is challenging do to compatibility issue between different library.
    3. SPring configuration is primarily xml based while spring boot has annotation driven configuration, yielding concise, readable and clean code.
    4. Spring requires manual configuration of beans and dependency vs spring boot has auto component scanning.
    5. In Spring we need to write lots of boilerplate code while Spring Boot reduces boilerplate code thus reducing LOC
  17. Dependency Injection - Its need, how it works in Spring boot ?

    IOC: IOC is a software design principle where the control of object creation and lifecycle management is shifted from the application code to a framework (like Spring). a. Object Creation and Management: IOC manage the lifecycle of object. b. Dependency Injection: IoC container automatically injects dependencies into beans, eliminating the need for manual wiring c. Configuration: IoC container reads configuration metadata from various sources, such as XML files, Java annotations, or Java configuration classes d. AOP Integration: The IoC container integrates with Spring AOP to provide cross-cutting concerns like logging, security, and transaction management.

    Benefits of IOC:

    1. Loose Coupling
    2. Reduced Boilerplate Code
    3. Improved Maintainability

    Dependency Injection (DI) is a design pattern used in software development where an object receives its dependencies from an external source rather than creating them itself.

    1. IOC container scans the application for component annotated with @component, @Service , @Repository and automatically wires them as dependency.
    2. Injection happens using constructor, setter and field.
    3. IoC (Inversion of Control) container creates and stores the objects (beans) in a Bean Factory or ApplicationContext, depending on the configuration.
  18. Cron job sample and annotation

  19. How to handle the exception occurance in a cron job.

  20. What is AOP ? Give me a sample AOP program ?