SpringBoot Interview Q & A
Here are some tricky Spring Boot interview questions along with their answers to help you prepare effectively:
1. What happens if you annotate a class with @Component
, @Service
, and @Repository
together?
Spring will treat the class as a single bean because all three annotations are meta-annotated with @Component
. The application context will not create multiple instances. However, using all three together is not a good practice—it’s better to use the most relevant annotation based on the class’s role.
2. Can you use @Autowired
inside a static method?
No, Spring does not inject dependencies into static methods because Spring beans are managed at the instance level. To access Spring beans inside static methods, you should use ApplicationContextAware
.
public class StaticUtil {
public static void performTask() {
MyService service = BeanUtil.getBean(MyService.class);
service.doSomething();
}
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
// Spring injects the ApplicationContext into this method
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
// Static method to access the ApplicationContext
public static ApplicationContext getApplicationContext() {
return context;
}
// Static method to fetch a bean by its class
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
// Static method to fetch a bean by its name
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
3. What will happen if @PostConstruct
is used in a @Configuration
class?
- The method annotated with
@PostConstruct
will execute once after the bean is initialized. - However, in a
@Configuration
class, it might behave unexpectedly if you create multiple@Bean
methods inside it.
@Configuration
public class AppConfig {
@PostConstruct
public void init() {
System.out.println("Init method called");
}
@Bean
public MyService myService() {
return new MyService();
}
}
--------------Output------
Init method called
It runs once when the configuration class is loaded.
4. What is the difference between @PostConstruct
and InitializingBean
?
Which one should you use?@PostConstruct
is preferred because it is a standard Java annotation, while InitializingBean
is Spring-specific.
5. What happens if a bean implements both InitializingBean
and has @PostConstruct
?
Both methods will execute, but @PostConstruct
runs first, followed by afterPropertiesSet()
.
@Component
public class TestBean implements InitializingBean {
@PostConstruct
public void postConstruct() {
System.out.println("@PostConstruct executed");
}
@Override
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet executed");
}
}
-----------OUTPUT------
@PostConstruct executed
afterPropertiesSet executed
Order is like :
@PostConstruct
afterPropertiesSet()
6. How does Spring handle circular dependencies in @Autowired
?
Spring detects circular dependencies and throws BeanCurrentlyInCreationException
.
Example of Circular Dependency:
@Component
public class A {
@Autowired private B b;
}
@Component
public class B {
@Autowired private A a;
}
This will cause an error!
How to Fix Circular Dependencies?
1️⃣ Use @Lazy
on one of the dependencies:
@Component
public class A {
@Autowired @Lazy private B b;
}
2️⃣ Use ObjectFactory
or Provider
(Recommended for larger projects)
@Component
public class A {
@Autowired private ObjectProvider<B> b;
}
7. Can you inject a prototype-scoped bean into a singleton bean?
Yes, but Spring does not manage prototype beans after creation, so the same instance will be used in the singleton bean.
✅ Solution: Use ObjectProvider
or @Lookup
@Component
public class SingletonBean {
@Autowired private ObjectProvider<PrototypeBean> prototypeBeanProvider;
public void usePrototypeBean() {
PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
System.out.println(prototypeBean);
}
}
8. What is the difference between @ComponentScan
and @EntityScan
?
@SpringBootApplication
@ComponentScan(basePackages = "com.example.services")
@EntityScan(basePackages = "com.example.entities")
public class MyApplication {
}
9. What happens if there are multiple beans of the same type and @Autowired
is used?
Spring throws NoUniqueBeanDefinitionException
because it cannot determine which bean to inject.
Solutions:
1️⃣ Use @Primary
to mark a default bean
@Primary
@Component
public class DefaultService implements MyService { }
2️⃣ Use @Qualifier
to specify which bean to use
@Bean("serviceA")
public MyService serviceA() { return new ServiceA(); }
3️⃣ Use @Bean
with specific names in @Configuration
@Bean("serviceA")
public MyService serviceA() { return new ServiceA(); }
10. Can we have multiple @SpringBootApplication
classes in a project?
Yes, but only one should be the main entry point for SpringApplication.run()
.
If you have multiple, Spring may not know which one to start.
✅ Solution:
- Specify which one is the main class explicitly:
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
11. What happens if @Component
and @Bean
are used together for the same class?
@Component
is used for auto-detection (class-level).@Bean
is used in a@Configuration
class for manual bean registration.- If both are used together for the same class, Spring will create two separate bean instances.
@Component
public class MyService {
}
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
📌 Two beans will be created:
- One from
@Component
- One from
@Bean
method
🔴 Avoid this to prevent multiple unwanted instances.
12. Can we create a bean without using @Component
, @Service
, or @Repository
?
Yes, we can use @Bean
inside a @Configuration
class.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
This is useful when we don’t have access to modify third-party classes.
13. What is the difference between @Scope("singleton")
and @Scope("prototype")
?
@Component
@Scope("prototype")
public class PrototypeBean {
}
Each time context.getBean(PrototypeBean.class)
is called, a new instance is created.
11. What happens if @Component
and @Bean
are used together for the same class?
@Component
is used for auto-detection (class-level).@Bean
is used in a@Configuration
class for manual bean registration.- If both are used together for the same class, Spring will create two separate bean instances.
@Component
public class MyService {
}
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
📌 Two beans will be created:
- One from
@Component
- One from
@Bean
method
🔴 Avoid this to prevent multiple unwanted instances.
12. Can we create a bean without using @Component
, @Service
, or @Repository
?
Yes, we can use @Bean
inside a @Configuration
class.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
This is useful when we don’t have access to modify third-party classes.
13. What is the difference between @Scope("singleton")
and @Scope("prototype")
?
@Component
@Scope("prototype")
public class PrototypeBean {
}
Each time context.getBean(PrototypeBean.class)
is called, a new instance is created.
14. Can we inject a prototype
bean inside a singleton
bean?
Yes, but Spring does not manage prototype beans after creation.
The same instance of the prototype bean will be injected once.
🔴 Wrong Way (causes stale prototype bean issue)
@Component
public class SingletonBean {
@Autowired private PrototypeBean prototypeBean;
}
📌 Fix using ObjectProvider
or @Lookup
@Component
public class SingletonBean {
@Autowired private ObjectProvider<PrototypeBean> prototypeBeanProvider;
public void usePrototypeBean() {
PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
System.out.println(prototypeBean);
}
}
15. What is @Lookup
annotation?
It is used to dynamically inject prototype beans inside singleton beans.
@Component
public abstract class SingletonBean {
public void usePrototypeBean() {
PrototypeBean prototypeBean = getPrototypeBean();
System.out.println(prototypeBean);
}
@Lookup
protected abstract PrototypeBean getPrototypeBean();
}
📌 Spring will override getPrototypeBean()
at runtime to return a new instance each time.
16. Can we run multiple Spring Boot applications in the same JVM?
Yes, but we must ensure that they use different ports.
✅ Solution: Set random ports in application.properties
server.port=0
OR
@SpringBootApplication
public class Application1 {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application1.class);
app.setDefaultProperties(Collections.singletonMap("server.port", "8081"));
app.run(args);
}
}
17. What is the difference between @Transactional
on method vs. class level?
- Class Level: Applies to all methods in the class.
- Method Level: Applies only to that specific method.
@Service
@Transactional
public class PaymentService {
public void processPayment() { } // Transactional
public void refundPayment() { } // Transactional
}
@Service
public class OrderService {
@Transactional
public void placeOrder() { } // Only this method is transactional
}
📌 If placed at the class level, all methods inside are transactional.
18. What is the default propagation type of @Transactional
?
The default is Propagation.REQUIRED
, which means:
- If there’s an existing transaction, the method joins it.
- If no transaction exists, a new one is created.
@Transactional
public void methodA() { } // Transaction starts
public void methodB() { } // Runs in the same transaction as methodA
19. What is the difference between @RestController
and @Controller
?
The @RestController
and @Controller
annotations in Spring MVC serve different purposes, primarily in how they handle HTTP responses.
@Controller
public class WebController {
// Returns a view (e.g., home.html)
@GetMapping("/home")
public String home() {
return "home";
}
// Returns JSON data (requires @ResponseBody)
@ResponseBody
@GetMapping("/data")
public String getData() {
return "Hello, World!";
}
}
@RestController
public class ApiController {
// Returns JSON: {"message": "Hello, World!"}
@GetMapping("/api/data")
public Map<String, String> getData() {
return Map.of("message", "Hello, World!");
}
}
Key Differences
📌 @RestController
= @Controller + @ResponseBody
20. How to handle exceptions globally in Spring Boot?
Use @ControllerAdvice
and @ ExceptionHandler
.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
📌 This applies globally to all controllers.
21. What are the differences between @RequestParam
and @PathVariable
?
@GetMapping("/users")
public String getUser(@RequestParam String name) {
return "User: " + name;
}
@GetMapping("/users/{id}")
public String getUserById(@PathVariable int id) {
return "User ID: " + id;
}