Spring boot interview question
Created on: Sep 30, 2024
-
What is a web server ? A web server is a software system that hosts websites and delivers web content to users over the Internet.
-
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.
-
How to get different scope of beans in spring boot application.
@Scope("prototype"), @Scope("singleton")Other Scope are:
- request
- session
- application
- WebSocket
-
When to not use spring boot application ?
- Resource-Constrained Environments: If your application needs to run on devices with severely constrained memory
- High-Performance, Low-Latency Requirements: For applications with strict real-time requirements custom solution is better.
- Migrating a large, heavily configured legacy project to Spring Boot can be challenging
-
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.
-
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.
-
How to initialize bean only if a condition matches in spring boot
- Using
@Conditionalannotation
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(); } }- 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(); } }- 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(); } }- @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(); } } - Using
-
Difference between Spring Data JPA and Hibernate ?
Feature Hibernate Spring Data JPA Level of Abstraction Lower-level Higher-level Boilerplate Code More Less Query Mechanisms JPQL, SQL, Criteria API Method-based queries, JPQL, SQL Integration with Spring Integrates well Tightly integrated with Spring ecosystem Important Points:
- By default Spring uses Hibernate as the default JPA vendor.
- JPA is not an implementation. It is only a Java specification.Hibernate is an implementation of JPA.
- Other implementation of JPA are EclipseLink, OpenJPA
-
What are the various annotation used in Spring, spring boot application and JPA application ?
- @GeneratedValue: Specifies how the primary key value should be generated
- @GeneratedValue -> @GeneratedValue(strategy = GenerationType.IDENTITY). primary key value is generated by the database itself, typically using an auto-increment column
- Auto - Lets JPA decide the strategy based on the database.
- Sequence - Uses a database sequence object to generate unique values
- UUID ->
- TABLE - Uses a separate database table to generate unique values.
- @Entity annotation marks this class as a JPA entity
- @Table annotation specifies the name of the database table to map to
- @Id annotation marks the id field as the primary key of the table
- @GeneratedValue: Specifies how the primary key value should be generated
-
What is dependency Injection and IOC in spring boot.
-
DIfference between Spring and spring boot.
-
Difference between
-
What is difference between @Controller and @Service vs @Repository.
-
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.
-
What are the types of beans and how to create them in spring boot.
- SIngleton
- Prototype
-
What are the difference between spring vs spring boot ?
- Spring boot includes embedded tomcat server or jetty while spring relies on external webserver like tomcat.
- 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.
- SPring configuration is primarily xml based while spring boot has annotation driven configuration, yielding concise, readable and clean code.
- Spring requires manual configuration of beans and dependency vs spring boot has auto component scanning.
- In Spring we need to write lots of boilerplate code while Spring Boot reduces boilerplate code thus reducing LOC
-
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:
- Loose Coupling
- Reduced Boilerplate Code
- 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.
- IOC container scans the application for component annotated with @component, @Service , @Repository and automatically wires them as dependency.
- Injection happens using constructor, setter and field.
- IoC (Inversion of Control) container creates and stores the objects (beans) in a Bean Factory or ApplicationContext, depending on the configuration.
-
Cron job sample and annotation
-
How to handle the exception occurance in a cron job.
-
What is AOP ? Give me a sample AOP program ?
