What is circular/cyclic dependency in spring boot?
- When two services are interdependent on each other, that is to start one service, we require another service and to start second service, we require first service then we have a circular dependency.
- Circular dependency is also called as cyclic dependency.
- We face this dependency generally in constructor injection.
- We can use @Lazy Annotation in any service constructor to resolve this dependency.
How can we create a prototype Bean in Spring boot?
- @Component
- @Scope(“prototype”)
- Public Class SomeClass{
- }
How can we ensure quality and maintainability of code In our spring boot project?
- Ensure code reviews happen within peers.
- Unit test cases, which provide hundred percent coverage for services at least.
- Integration test cases.
- Use appropriate data structures and Algorithms.
- Follow coding standards.
- Use design pattern, such as MVC, MVVM or MVP.
- Test your code thoroughly.
- Use version control system.
- Write, clear and concise and Modular code.
- Follow some documentation for your code.
Spring Boot Application perform slower in the production environment, then the development set up. What steps will you take to address this issue?
- Auto-wiring
- Don’t use it for classes with static methods.
- Avoid auto-wiring collection beans.
- Private List<MyService> services
- Manually manage the collection and only auto-wire the class.
- Use constructor injection instead of field injection.
- Constructor injection is a recommended For better testability and to avoid issues with final fields.
- When multiple beans of same type exist, Use @Primary To specify, which bean should be preferred.
- When you want to explicitly specify, which one among the beams, you want to use, Use @Qualifier.
- Lazy initialisation
- Use @Lazy if a bean should only be created when it is first needed. This can improve start-up time and resource usage.
- Connection Pooling
- Connection pooling Improves performance by reusing existing database connections Instead of opening a new connection for every request.
- This optimisation technique involves maintaining a pool of open connections rather than opening a new database connection for each API call.
- Creating a new connection, each time involve a lot of handshake protocols and set up Which can slow down the API.
- The reuse of connections Can greatly improve throughput.
- This reduces The overhead of establishing connections and provides efficient management of database resources.
- Hickari Connection pool is default choice in spring boot for its high-performance.
- Ensure that transactions are managed appropriately, specially in spring application, where transactions are typically handled declaratively.(@Transactional)
- Monitor and analyse connection problems, such as active connections, ideal connections, connection wait time, and pool utilisation.
- Use try with resources to ensure that Connections are properly closed after use, even in the event of exceptions.
- Instead of opening a fresh connection, each time clients will use pre-opened connection from a pool and once done with transaction, they can release the connection back to the pool.
- For server-less architecture Connection management can be a bit more challenging
- This is because each server-less function Instance, typically opens its own database connection.
- And because server-less Can scale rapidly, this could potentially lead to a large number of connections that could overwhelm the database.
- Solutions like AWS RDS proxy And Azure SQL database server less are designed to handle this situation and manage connection pooling for you.
- Async Processing
- Asynchronous processing Allows tasks to run in the background, improving the responsiveness and performance of your application.
- This is particularly useful for long running tasks that do not need to block the main thread.
- Asynchronous processing is benefit for Tasks that
- Are I/O intensive (eg file operations, network calls)
- Take significant amount of time to complete.
- Do not require immediate results to proceed.
- Example
- An application needs to send confirmation emails to users
- An application allows users to upload files, And the files need to be processed after uploading.
- Annotate the main class or a configuration with @EnableAsync
- Annotate the method of a class which has business logic with @Async and let it return a future or Completable future Object.
- Manage a thread pool using An executor framework.
- Asynchronous Logging
- The main application, thread Can place the log entry into memory buffer, While a separate logging thread Write the log entries To the file or send them to the logging, service.
- With asynchronous, logging We might loose Some logs, if our application crashes before the logs have been written.
- We can have a separate process to perform logging instead of the logging being done by the process serving the request.
- We can use a separate process, service, messaging broker, or a separate thread All together to manage our logging.
- Use different logging levels(Error,Warn,Info,Debug,Trace) Based on the importance And frequency of the log messages.
- In Development and testing Use Trace and Debug Levels to gain detailed insights Into the application behaviour and identify bugs.
- In production, we use Info,Warn, And error levels To monitor the applications, health, and performance without Generating excessive log data.
- For critical Alerts use fatal for logging critical issues that require immediate attention and may cause the application to terminate.
- Use Minimal logger instances. Avoid creating too many logger instances. Reuse logger instances whenever possible.
- Private static final logger = LoggerFactory.getLogger(My.class)
- Use Mapped Diagnostic Context. Add context information like user IDs, transaction ID to log messages to make the debugging easier without cluttering logs.
- Use MDC to inject identifier(eg Correlation Id’s) into logs to trace individual request across multiple services.
- It works like a hash-map It uses key value pairs.
- Mapped Diagnostic Context(MDC) Is a feature provided by logging frameworks like logback, And log4j That allows you to en which log into is with context, specific information.
- This context can include details such as user IDs, transaction IDs or session IDs Which are crucial for understanding the flow of a request across different parts of an application.
- MDC uses thread, local storage, meaning that the context data is Local to the thread That sets it. This ensures that the Contextual information is not shared between threads.
- The %{key} pattern in logging configuration file will include the MDC value associated with the key in each log message.
- Always clear MDC values after the request is processed to avoid unintentionally leakage of context, data between requests.
- Use asynchronous logging To offload logging operations to a separate thread, Reducing latency in the main application thread.
- Use structural logging to capture logs in a format that is easy to parse and analyse Example, Jason format.
- Add context, such as request, IDs, user IDs, and session ID to logs for better traceability and debugging.
- Logging.pattern.console=%d{YYYY-MM-DD HH:mm:ss}=%msg%n
- Logging.pattern.file=%d{YYYY-MM-DD HH:mm:ss}= %msg%n
- Exclude sensitive data from logs to ensure security and compliance with data protection regulations.
- Configure log rotation and archiving to prevent log files from growing indefinitely and Consuming disk space.
- Utilise tools like ELK stack(Elastic search, logstash, kibana), Splunk or Gary Log First centralised log management and analysis.
- Temporarily disable Logging in performance – critical code sections, if necessary.
- Database optimisation.
- Optimise SQL queries to fetch only necessary data. Use joins and subqueries Wisely to minimise the number of separate database calls.
- Use inner joint for mandatory relationships
- Use left joint for optional relationships
- Ensure proper indexing on join columns.
- Avoid fetching large text fields Or binary data unless necessary.
- Use pagination to limit the number of rows returned.
- Use batch possessing to handle multiple operations in a single transaction.
- Batch insert, update, or delete operations to minimise the number of database round trips.
- Use native sql queries For complex operations that are not supported by JPQL.
- N+1 problem
- The N plus one problem is a common performance issue that occurs when an application needs to fetch data that is related across multiple tables. It typically happens in ORM(Object relational mapping) Framework like hibernate when a developer unintentionally triggers additional database queries.
- An N+1 problem occurs if we first make a query to fetch initial data, and then we again make multiple queries to fetch related data.
- If we have initial N data Then we will have one query for the initial data and N queries for related data.
- To avoid this, it’s more efficient to fetch the data in a single query, Or in some cases, two queries.
- One to fetch initial data And in second fetch, all the related data of all initial data all together.
- Then segregate the related data based on initial data based on some business logic.
- For Initial query Fetch a list of employees, and we are also fetching departments along with that.
- @Query(“Select e from Employee e Join Fetch e.department”)
- When using a join against an entity, association, JPA will generate a join between the parent entity and the child entity tables in the generated SQL statement.The SQL Select clause contains only the employee table columns and not the department ones. To fetch the department table columns, we need to use join fetch instead of join.
- Create index columns for frequently used in Where,Join, and Order By clauses.
- Monitor and maintain indexes to avoid unnecessary overhead
- Use composite indexes for columns frequently queried together.
- Use subquery to filter data within a main query Efficiently.
- For any join fetch or fetch From multiple tables, use a single query which can be through join tables.
- Use a single query For fetching information for multiple ID’s , use where in (1,2,3,4).
- Caching
- If we have an end point that is most frequently accessed with the same request parameters, we can avoid repeated database hits by caching the response in Redis or Memcache.
- We store the result of an Expensive computation, so that we can use it again later without need to redo the Computation.
- Even a brief Period of caching Can make a significant difference in speed.
- Helps To reduce repeated database, request for similar data.
- We can use libraries like Redis,Memcached.
- Cache results of expensive operations like database queries, API calls, or complex calculations, not simple operations that fast to compute.
- Set appropriate expiration time(TTL-TimeToLive) For cache entries To ensure data consistency and avoid stale data.
- Ensure that application can handle cache misses gracefully By falling back to fetching data from The original source.
- Choose Right Cache Provider
- Select a cache provider Based on your applications needs. For small scale applications or development environments, In memory caches Like Ehcache or Caffine may suffice. For Larger, Distributed applications, Consider using distributed caches like Redis,Hazelcast,or Aerospike.
- Set Appropriate Cache Expiration.
- Configure Time to Live(TTL) and idle Timeouts To ensure cached data does not become stale.
- This Balances performance Benefits with data consistency. Determine times based on nature of your data and how frequently it changes.
- Monitoring
- Use monitoring tools to track cache metrics such as hit/miss ratios, Eviction counts, And cache size. Spring boot actuator Can help monitor these metrics. Regularly review these metrics to find tune your cache configuration For optimal performance.
- Cache only expensive operations
- Focus on caching Results of operations That are computationally expensive or involves slow input output, such as database queries, or API calls. Avoid caching Lightweight, operations or data that changes frequently To maximise the efficiency of your cache.
- Implement proper cache Invalidation
- Ensure your Application properly invalidates or updates cache entries when underlying data changes.Use annotations like @CacheEvict and @CachePut to manage cache In validation effectively, preventing the use of stale data And ensuring consistency.
- Pagination
- Read records in a paged fashion That is first, read first Hundred records, then next hundred records, then next hundred and so on. Getting all records at same time is time consuming.
- In our API response returns a large amount of data, it can slow things down. Instead, wake the response into smaller, more manageable pages using limit and offset parameters.
- This can speed up data transfer and reduce Load on client side.
- Use lightweight JSON serialiser
- When returning Jason responses from your API, the speed of your serialisation process can make a Noticeable difference in response Times.
- Use a fast serialisation library To minimise the time spent on converting your data into JSON format.
- Compression
- Whatever data we are passing As a request and whatever data, we are getting back as a response, we can add compression.
- Server Will add compression And client will decompress the data To use it.
- Using compression We can reduce the amount of data transferred over the network.The client then decompresses The data.
- We have efficient algorithms like Brotli That provide better compression ratio.
- Many content delivery networks(CDN) Like cloud flare handles compressions for us, thus offloading The task from our server.
- Consider using environment, variables or secure vaults to manage sensitive information.
- We can start by checking the logs for errors.
- Use monitoring tools to Track the performance metrics like memory usage, CPU load and Response time.
- Compare configuration between development and production to find differences.
- Database square is are fine. Tuned for performance.
- Check any external service used in the production affecting performance or not.
What is the difference between spring, spring boot, spring mvc?
- Spring boot
- Spring boot solves the configuration problem Of spring MVC
- We need to configure view resolver.
- We need to add web jar
- We need to Configure dispatcher servlet
- We need to do hibernate and JPA configuration.
- Spring boot bundles, all basic frameworks needed to build an application
- Spring-core, Beans, Context, AOP
- Web MVC-Spring MVC
- Jackson-For Json Implementation
- Validation-Hibernate Validator, Validation API
- Embedded servlet container-Tomcat
- Logging-Log back,slf4j
- Dev tools
- Actuator
- Spring boot comes up with a solution called as auto configuration and starters.
- Spring boot also provides tools to monitor and trace your applications.
- Spring boot starter, actuator.
- Spring boot is a composition of spring mvc and spring.
- Spring boot is used for individual micro services.
- Simplify development and production deployment.
- Minimal configuration convention over configuration.
- Opinionated Default with override options.
- Micro services, standalone applications, rapid development.
- Easier to learn and get started quickly.
- Reduced boilerplate code, followed convention over configuration.
- Growing community support.
- Spring MVC
- SPRING MVC Framework provides decoupled way of developing web applications. With simple concepts like dispatcher servlet, Model and view resolver, It makes it easy to develop the web applications.
- Spring MVC is used for web application
- Is based on model view controller framework.
- Specialised for building web applications
- Moderate Configuration(XML OR ANNOTATION)
- Flexible for Web applications
- Web applications with clear MVC architecture
- Moderate to learn for developers, familiar with web development
- Moderate boilerplate code for web components.
- Moderate, considering configuration and MVC patterns.
- Established community, specially for web development.
- Spring
- The core problem that spring framework solve is dependency injection.
- Spring is the problem of duplication or plumbing, the code.
- Spring JDBC
- Spring MVC
- SPRING AOP
- SPRING ORM
- SPRING JMS
- SPRING TEST
- Spring is used for large ERP systems.
- Spring is a general purpose frame for enterprise Java applications
- Extensive configuration is required(XML or Java Based)
- Highly flexible and customisable
- Used for large scale enterprise applications with complex requirements.
- Steeper learning curve.
- More boiler plate code due to extensive configuration.
- Slowed development speed due to detailed configuration.
- Large community support and well established community.
How can we integrate a relational database like My Sql With spring boot application?
- Add Database and Spring data JPA dependencies In the project, build file.
- Dependencies for string data JPA and Database and Hibernate if required must be added.
- Use Application properties file to set up the connection details.
- Add database URL.
- Add database username.
- Add database password.
- Configure hibernate properties, if required.
- Create a Spring Boot JPA account repository interface in code implementing JPA repository.
- Removes Boiler plate code from Application
- Removes DAO Layer from any application.
- Add @Component above repository.
- Create table entities using JPA entity.
- Convert spring boot domains to spring boot entity.
- @column,@id,@GeneratedValue to generate automatic ids.
- Use repository In service to perform CRUD operations.
- Add Support for JPA repository in service.
- Inject the repository in service And use methods like findOne(id),findAll(),save(),delete() to perform CRUD operations.
- Spring data JPA Or spring boot JPA does the integration between the spring application and JPA
- JPA stands for Java persistence API
- JPA is a collection of classes to persist data in database
- JPA perform a bridge between the object model POJO and relational database entity.
- JPA is a part of spring data
What is Auto configuration in spring boot?
- We use starter POM’s(Project Object Model)
- Spring boot starter Web
- Spring boot starter data JPA
- SPRING BOOT STARTER TEST
- Maven will pull all starter jars.
- All the spring boot auto configuration, JaR’s Present in file spring– boot–auto configure.jar.
- There is one jar of Auto configuration.
- This has folder META-INF
- It has file spring.factories.
- The file spring.factories defines all the Auto configuration.
- The classes become active based on some condition I.e Depending on the dependencies used
- For example, if we use JPA starter Then JPA Auto-configuration will get activated.
- Over each configuration class, we have animations like
- @ConditionalOnBean
- @ConditionalOnClass
- @ConditionalOnMissingBean
- These above annotations, define the missing beans.
- Without this, Auto configuration
- We had to configure Dispatcher servlet
- We had to configure data source
- Entity Manager factory
- Transaction factory and so on
- Auto configuration gives permission to spring boot to configure all the things it finds while scanning the context component, Path.
- Spring boot configuration Checks for all the spring boot, starter jars based on the dependencies used.
- For example, if a starter JPA will be enabled only once it has a database or when it wants to add a database.
- All the configuration of each starter jar package is defined in META-INF/spring.factories
How do we maintain environment specific properties in spring application?
- We maintain environment specific properties in spring application. In our application. Properties file.
- Spring cloud config server for centralised properties.
- Spring.active.profiles property for selecting currently active profiles.
- We use docker and Kubernetes yml file for Environment specific properties, which are provided by container.
What Parameters can be passed in HTTP Headers?
- Bearer Token
- Content Type
- Accept Header
- File Info
What is Idempotency?
- Idempotency is when we are continuously making a request, subsequently, and we are getting a same response.
- These calls are called as Idempotent calls.
- Example PUT is an Idempotent call.
How does @RequestMapping work?
- As soon as our application starts all the end points with @RequestMapping Get registered with dispatcher servlet. The request which comes from client is redirected to controller Or end point by dispatcher servlet.
How does spring boot make decision on which server to use?
- Spring boot decides based on class Path dependencies
- If a specific server dependency is present, like tomcat jetty etc Then spring boot configure it As default server. If no server dependency is found, then spring boot default to tomcat Which is included in spring boot starter web.
- This simplifies our set up and configuration
What is the use of actuator?
- Actuator is used to configure hystrix dashboard. It is used to check the heartbeat of a system or service. If the heartbeat is not available, it will disconnect the service from the service registry.
- We can use circuit breaker design pattern to have a fallback mechanism once the service is disconnected.
Which property is used to enable or disable actuator?
- The property used to enable or disable Actuator, can we defined in spring cloud gateway or application gateway. There we have YAML configuration We can provide hystrix properties To enable spring actuator.
- Every micro service, we can provide support for spring cloud framework.
- Spring boot is a spring module.
- Spring boot is a framework for RAD build.
- Using spring framework with extra support of Auto configuration and embedded application server like (tomcat, jetty).
- It provides RAD-rapid application development.
- It helps us in creating efficient fast standalone applications which you can just run it basically removes a lot of configurations and dependencies.
- Spring boot is lightweight.
- Spring boot Provide us with a ready to work Project out of box.
- Spring boot can easily integrate with other technologies.
- Spring boot can connect to database very easily.
- It provides security.
Q What are some of the key components of spring boot?
- Tomcat
- Starter dependencies, which are configured automatically.
- Actuator for health check.
- CLI used to create Standalone application.
Q How can we achieve RAD using Spring Boot?
- RAD is a modified waterfall model which focuses on developing software in a short span of time.
- Phases of RAD are as follows
- Business modelling
- Business model is designed for the product to be developed.
- Data modelling
- Data model is designed, the relation between these data objects are established using Info gathered in first phase.
- Process modelling
- Process model is designed. Process descriptions for adding, deleting, retrieving or Modifying a data object are given.
- Application generation
- The actual product is built using coding. Convert process and data models into actual prototypes.
- Testing and turnover
- Product is tested and if changes are required then whole process starts again.
Q Is it possible to change the port of embedded tomcat server in spring boot?
- Put “server.port” property in application.properties.
- Default port is 8080.
Q Can we override or replace the embedded tomcat server in spring boot?
- Yes we can replace the embedded tomcat with any other servers by using starter dependencies. Like we can use spring–boot–starter–jetty As a dependency for each project as you need.
- To exclude a dependency from spring boot starter web dependencies artefact use <exclusion> tag.
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusions>
- </exclusion>
Q Can we disable the default web server in the spring boot application?
- The major strong point in spring is to provide flexibility to build your application loosely coupled. Spring provides features To disable the web server in a quick configuration.
- Yes, we can use the application.properties to configure the web application type i.e spring.main.web–application–type = none.
Q How to disable a specific auto-configuration class?
- You can use the exclude attribute of @EnableAutoConfiguration, If you Find any specific auto–configuration classes that you do not want are being applied.
- @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
Q What does the @SpringBootApplication annotation do internally?
- As per the spring boot doc, the @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.
- Configuration helps us to identify beans for a particular spring dependency injection.
- EnableAutoConfiguration helps in “AutoScan” if a bean is available in our class Path it will be auto-scanned and added to our set of dependencies.
- ComponentScan Scans for our components or beans.
- Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, spring provided loosely coupled features that we can use for each individual annotation as per our project needs.
Q How to use a property defined in application.properties file into your Java class?
- Use the @Value Annotation to access the properties which is defined in the application–properties file.
- @Value(“${custom.value}”)
- private String customVal;
Q Explain @RestController annotation in spring boot?
- @RestController is convenience annotation for creating Restful controllers. It is a specialization of @Component and is auto detected to classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML.
- Which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.
- Indicates that the data returned by each method will be written straight into the response body instead of rendering a template.
Q Difference between @RestController annotation and @Controller in Spring Boot?
- It is that the response from the web application is generally view (HTML+CSS+JavaScript) because they are intended for human viewers while REST API just returns data in form of JSON or XML because most of the REST clients are programs.
- Same goes with @RestController and @Controller annotation.
- @Controller Map of the model object to view or template and makes it human readable.
- @RestController simply returns the object and object data is directly written into HTTP response as JSON or XML.
Q What is the difference between GetMapping and RequestMapping?
- Request mapping can be used with GET, POST, PUT, and many other request methods using the method attribute on the annotation. Whereas GetMapping is only an extension of RequestMapping, which helps you to improve clarity on requests.
Q What is the use of profiles in Spring Boot?
- When developing applications for the enterprise, we typically deal with multiple environments such as Dev, QA, and Prod. The configuration properties for these environments are different.
- For example, we might be using embedded H2 database for Dev, but Prod could have the proprietary Oracle or DB2. Even if the DBMS Is same across environments, the URLs would definitely be Different.
- To make this easy and clean, spring has the provision of profiles, to help separate the configuration for each environment. So that instead of maintaining this programmatically, the properties can be kept in separate files such as application-dev.properties and application –prod.properties. The default application.properties points to the currently active profile using spring .profiles.active so that the current configuration is picked up.
What is the use of @value In spring boot.
- Using this we can read value from properties file
How can we use multiple databases in a service?
- For different environments, we can use profile and then in each profile configuration. Accordingly, we can activate different databases.
- For single environment, we can have different data sources and for each data source, we can have database template. We can also use factory pattern to return object of different Data Source.