Experienced Spring/Spring Boot Interview Questions for Java Developers-2023[5–10 years]

This article explores recently encountered interview questions for experienced Java developers who are familiar with Spring and Spring Boot. These questions are designed to assess one’s in-depth knowledge of the Spring framework and its Spring Boot.

Ajay Rathod
Level Up Coding

--

Are you preparing for a job interview as a Java developer?

Find my book Guide To Clear Java Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).

Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).

Download the sample copy here: Guide To Clear Java Developer Interview[Free Sample Copy]

Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]

here are previous articles if you have missed them,

Spring and SpringBoot

What is an alternative to spring boot application annotation?

It is generally recommended to use the @SpringBootApplication annotation, as it is more concise and easier to remember.

The alternative to the @SpringBootApplication annotation is to use the following annotations individually:

@Configuration: This annotation marks a class as a configuration class, which means that it can be used to register beans with the Spring Boot application context.
@EnableAutoConfiguration: This annotation enables Spring Boot’s auto-configuration feature, which automatically configures the Spring Boot application based on the dependencies that are present on the classpath.
@ComponentScan: This annotation enables component scanning, which means that Spring Boot will automatically scan the specified packages for annotated components, such as @Controller, @Service, and @Repository.

we have to use the above annotation manually,

Let's say we don't want to build the application using spring boot then, Micronaut, Quarkus, and Vert. x are the other options available we can go for that.

Which bean scope takes a lot of computational memory?

This question is related to spring bean scopes, in order to answer you should know the definition of each bean and how they behave,’

based on that we can answer,

There are four types of bean scopes,

1) singleton: Returns a single bean instance per Spring IoC container.

the container creates a single instance of that bean; all requests for that bean name will return the same object, which is cached. Any modifications to the object will be reflected in all references to the bean. This scope is the default value if no other scope is specified

2) prototype: Returns a new bean instance each time when requested.

prototype scope will return a different instance every time it is requested from the container. It is defined by setting the value prototype to the @Scope annotation in the bean definition

3) request: Returns a single instance for every HTTP request call.

4) session: Returns a single instance for every HTTP session.

The answer to this is Prototype bean.

Difference between @inject and @autowire?

The @Inject and @Autowired annotations are both used for dependency injection in Spring. However, there are a few key differences between the two:

Origin: The @Inject annotation is part of the Java Contexts and Dependency Injection (CDI) specification, while the @Autowired annotation is specific to the Spring framework.

Required dependencies: By default, the @Inject annotation will throw an exception if the required dependency cannot be found. However, the @Autowired annotation can be configured to allow optional dependencies.

Scope: By default, the scope of beans injected with the @Inject annotation is prototype. However, the scope of beans injected with the @Autowired annotation is singleton.

Additional features: The @Autowired annotation has a number of additional features, such as the ability to specify a qualifier for the dependency and the ability to inject a provider for the dependency.

In general, it is recommended to use the @Inject annotation if you want to write code that is not tied to a specific framework or container.

What is bean lifecycle?

Remember on a high level,

Spring follows these steps:

Init() — initializing the bean

Service() — using the bean

Destroy() — cleanup the bean

What kind of exceptions you have seen in the Springboot project?

By asking this question the interviewer is checking, if you have worked on a spring boot project or not. If you have worked you can answer and then follow the spring exceptions-related questions.

if you don't know these are common exceptions in the spring and spring-boot framework.

BeanCreationException: This exception is thrown when Spring fails to create a bean. This can happen for a variety of reasons, such as a missing dependency, a configuration error, or a runtime exception.
NoSuchBeanDefinitionException: This exception is thrown when Spring cannot find a bean definition for the specified bean name. This can happen if the bean is not defined in the Spring configuration or if the bean definition is invalid.
Additionally, I have seen, CircularDependencyException, DataAccessException, ConstraintViolationException, and NoHandlerFoundException.

You guys can answer based on the experience you had with this framework.

How to write Springboot custom annotation or any custom annotation in Java?

Java helps you to write custom annotations based on your requirements.

In order to do that you have to follow these steps, Remember these are the questions asked only to experienced Java programmers, not the fresher guys,

To write a Spring Boot custom annotation, follow these steps:

  1. Create a Java interface and annotate it with the @Retention and @Target annotations. The @Retention annotation specifies how long the annotation should be retained. The @Target annotation specifies where the annotation can be used.
  2. Define the members of the annotation. The members can be methods, fields, or constructors.
  3. Implement the annotation. This is optional, but it can be useful for providing additional functionality or validation.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyController {

}

How to connect multiple DB in spring-boot?

Many times this question is asked in an interview to check your experience in spring boot, just go through the below steps to answer the question.

it's very less likely you will be asked to write the code.

To connect to multiple databases in Spring Boot, follow these steps:

  • Add the necessary database dependencies to your project.
    - Configure your database connections in the application.properties or application.yml file.
    - Create a DataSource bean for each database connection using the @Bean annotation.
    - Create a TransactionManager bean for each database connection using the @Bean annotation.
    - Inject the DataSource and TransactionManager beans into your application code using the @Autowired annotation.
    - Use the DataSource and TransactionManager beans to interact with your databases.

What happens when you don’t annotate the JPA repository with @repository annotation?

If you don’t annotate your JPA repository interface or class with @Repository, the following might happen:

Component Scanning: Your repository might not be automatically detected and registered as a Spring bean, which means you would need to create an explicit bean definition for it in your Spring configuration.

Exception Translation: Spring Data JPA might not provide exception translation for JPA-specific exceptions, making it more challenging to handle these exceptions in a consistent way.

Transaction Management: Spring may not automatically apply transaction management to the repository methods. You would need to manage transactions manually or configure them explicitly for the repository methods using other Spring mechanisms, such as @Transactional annotations.

In practice, it’s a good practice to annotate your JPA repositories with @Repository to take advantage of these benefits and ensure that your repositories are properly managed by Spring. However, not annotating with @Repository doesn’t prevent you from using JPA repositories; i

Why use spring data JPA?

It reduces boilerplate code, enhances productivity, and offers features like automatic query generation, paging, and sorting, making database operations more efficient and developer-friendly.

Why go for native queries?

Using native queries in a Java application with JPA (Java Persistence API) has some advantages and scenarios where it can be beneficial:

Complex Queries: Native queries allow you to write complex SQL queries that might be challenging or impossible to express using JPA’s JPQL (Java Persistence Query Language). If your application requires complex database operations, native queries can be more expressive and efficient.

Performance Optimization: In some cases, native queries can perform better than JPQL queries because they allow you to take advantage of database-specific optimizations or features. You have fine-grained control over the SQL generated for a query.

Legacy Databases: When working with legacy databases, the schema might not align well with JPA entities. In such cases, native queries can help you interact with the database more seamlessly.

Database-Specific Features: If your application relies on database-specific features or functions that are not supported by JPA or JPQL, native queries enable you to leverage those features directly.

Where do we create an instance of entity manager?

This question helps in understanding if you have worked on entity manager or not in the hibernate framework.

Generally, we write entity manager in the service class,

in a Spring-based JPA application, you don’t need to create the EntityManager manually. Spring manages it for you through either Spring Data JPA or by injecting it into your Spring-managed beans using annotations like @PersistenceContext.

How to trace a request in spring-boot?

There are multiple ways in which we can achieve this scenario,

Spring Boot Actuator provides built-in endpoints for monitoring and tracking,

use these endpoints “/actuator/httptrace” and “/actuator/metrics”

However, the industry uses Third-Party Monitoring Tools Spring Cloud Sleuth, Zipkin, or Prometheus for more advanced request tracing and performance monitoring.

Sleuth is used for most of the distributed tracing environment. where we can see a particular request flowing from one end to another.

How will you write a program to upload a file in an s3 bucket using Springboot?

Nowadays Springboot + AWS is commonly used to develop cloud-based solutions. One of the scenarios being asked is how can we upload a file in s3 and write code to check the familiarity with it.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

@RestController
@RequestMapping("/api/s3")
public class S3Controller {

@Autowired
private S3Client s3Client;

@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket("YOUR_BUCKET_NAME")
.key(fileName)
.build();

s3Client.putObject(objectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));

return "File uploaded successfully to S3: " + fileName;
} catch (Exception e) {
return "File upload failed: " + e.getMessage();
}
}
}

How to do bulk upload in s3 using Springboot?

To upload the file in bulk we need to use the MultipartFile upload strategy like this below,

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/s3")
public class S3BulkUploadController {

@Autowired
private S3Client s3Client;

@PostMapping("/bulk-upload")
public String uploadMultipleFiles(@RequestParam("files") List<MultipartFile> files) {
try {
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket("YOUR_BUCKET_NAME")
.key(fileName)
.build();

s3Client.putObject(objectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
}

return "Bulk upload completed successfully";
} catch (IOException e) {
return "Bulk upload failed: " + e.getMessage();
}
}
}

Conclusion

The series of questions mentioned above is intended for Java developers with 8–9 years of experience. It’s evident from these questions that they require a deep and extensive understanding of the subject matter. Simply reviewing these questions can help you identify the specific topics to focus on during your preparation.

Thanks for reading

  • 👏 Please clap for the story and subscribe 👉(you can give upto 50 likes)
  • 📰 Read more content on my Medium (30+ stories on Java Developer interview)

Find my books:

--

--

Software Engineer @Cisco | Java Programmer | AWS Certified | Writer | Find My Books on Java Interview here - https://rathodajay10.gumroad.com/