Saturday, 5 April 2025

 

🎯 10 Tricky Spring Boot Bean Creation Interview Questions (With Answers)

Knowing how Spring Boot manages beans is critical for backend interviews. Here's a curated list of tricky but real-world interview questions, each with a sharp, confident answer you can use in your blog or interviews.


βœ… 1. How many instances of a @Component bean are created by default in Spring Boot?

βœ”οΈ Answer:

Only one instance is created per Spring container. This is due to the default singleton scope in Spring.

Bonus: You can verify this by comparing two injected references or printing the bean hashcode.


βœ… 2. How do you create a new object of a bean every time it's needed?

βœ”οΈ Answer:

Use the @Scope("prototype") annotation:


@Component @Scope("prototype") public class MyService { ... }

Now Spring will create a new instance every time the bean is requested.


βœ… 3. Can you use @Autowired with prototype-scoped beans?

βœ”οΈ Answer:

Yes, but be careful!

  • If injected directly via @Autowired, Spring injects only once (at startup).

  • To get a new object every time, use ObjectFactory or Provider:


@Autowired private ObjectFactory<MyPrototypeBean> factory; factory.getObject(); // gives new instance each time

βœ… 4. How does Spring Boot know which beans to create?

βœ”οΈ Answer:

Spring Boot uses @ComponentScan (inside @SpringBootApplication) to automatically detect classes annotated with:

  • @Component

  • @Service

  • @Repository

  • @Controller


βœ… 5. How to find out how many beans Spring has created at startup?

βœ”οΈ Answer:

In your main class:


ApplicationContext ctx = SpringApplication.run(MyApp.class, args); System.out.println("Bean count: " + ctx.getBeanDefinitionCount());

βœ… 6. Can you have multiple beans of the same type? How does Spring know which one to inject?

βœ”οΈ Answer:

Yes, and you can resolve conflicts using:

  • @Primary – Marks a bean as default

  • @Qualifier("beanName") – Specifies the exact bean to inject


βœ… 7. What happens if two beans implement the same interface and no qualifier is used?

βœ”οΈ Answer:

Spring throws a NoUniqueBeanDefinitionException, because it doesn't know which bean to inject.


βœ… 8. What’s the difference between @Bean and @Component?

βœ”οΈ Answer:

@Component@Bean
Used on classesUsed on methods inside @Configuration
Automatically discoveredExplicitly declared
Can't customize easilyFine-grained control of object creation

βœ… 9. How do you define a lazy-loaded bean?

βœ”οΈ Answer:

Use @Lazy:


@Component @Lazy public class MyBean { ... }

Now Spring creates the bean only when it’s first requested, not at startup.


βœ… 10. Can Spring Boot manage third-party objects (e.g., not annotated with @Component)?

βœ”οΈ Answer:

Yes! Register them using @Bean:


@Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }

Spring will manage the lifecycle just like any other bean.


🧠 Bonus Tip: Must-Know Keywords for Interviews

"Spring Boot scans for beans using annotations like @Component. By default, it uses singleton scope, but we can switch to prototype or request. The container handles bean lifecycle and dependency resolution using IoC and DI principles."

 

🌱 How Objects (Beans) Are Created in Spring Boot – Explained with Examples

In Spring Boot, objects are managed by the Spring container and are known as beans. Unlike regular Java classes, Spring controls the creation, lifecycle, and scope of these objects.

In this blog, you’ll learn:

  • How objects are created in Spring Boot

  • How many instances are created

  • Bean scopes (singleton, prototype, etc.)

  • Real code examples


🧠 What Is a Spring Bean?

A Spring Bean is simply a Java object that is instantiated, assembled, and managed by Spring's IoC container.

You register a bean by using:

  • @Component

  • @Service

  • @Repository

  • @Controller

  • or manually via @Bean in a config class


βœ… Default Object Creation – Singleton Scope

By default, Spring Boot creates only one instance of a bean per container. This is called the singleton scope.

πŸ”§ Example:


@Component public class MyService { public MyService() { System.out.println("MyService bean created!"); } }

@RestController public class MyController { @Autowired private MyService service1; @Autowired private MyService service2; @GetMapping("/test") public String test() { return "Are both services same? " + (service1 == service2); } }

πŸ’‘ Output:

MyService bean created! Are both services same? true

βœ… Only ONE object is created, reused across the app.


πŸ”„ Changing Scope: Prototype (New Object Every Time)

If you want a new object each time, use @Scope("prototype").

πŸ”§ Example:


@Component @Scope("prototype") public class MyPrototypeService { public MyPrototypeService() { System.out.println("PrototypeService instance created!"); } }


@RestController public class TestController { @Autowired private ApplicationContext context; @GetMapping("/proto") public String test() { MyPrototypeService s1 = context.getBean(MyPrototypeService.class); MyPrototypeService s2 = context.getBean(MyPrototypeService.class); return "Are both prototype beans same? " + (s1 == s2); } }

πŸ’‘ Output:


PrototypeService instance created! PrototypeService instance created! Are both prototype beans same? false

βœ… Two objects created, one per request to getBean().


πŸ§ͺ Other Bean Scopes

ScopeDescription
singleton(Default) One instance per Spring container
prototypeNew instance every time the bean is requested
requestOne instance per HTTP request (Web apps only)
sessionOne per HTTP session
applicationOne per ServletContext

🧠 How Are Beans Created Internally?

Internally, Spring Boot uses reflection and dependency injection:

  1. Scans for annotated classes using @ComponentScan

  2. Creates bean definitions (BeanDefinition)

  3. Resolves dependencies using constructor injection or field injection

  4. Manages lifecycle (@PostConstruct, @PreDestroy, etc.)


🧩 Example: Constructor Injection


@Component public class A { public A() { System.out.println("A created"); } } @Component public class B { private final A a; @Autowired public B(A a) { this.a = a; System.out.println("B created with A"); } }

Spring creates A first, then passes it to B automatically.


πŸ‘¨β€πŸ”¬ How to List All Beans Created by Spring Boot?

Add this to main():


public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(MyApp.class, args); String[] beans = ctx.getBeanDefinitionNames(); Arrays.sort(beans); for (String name : beans) { System.out.println(name); } }

βœ… You'll see all objects created by Spring, including yours and internal framework beans.


πŸ” Singleton vs Prototype – When to Use?

Use CaseScope to Choose
Shared service (e.g. logging)singleton
Non-thread-safe objectsprototype
Per-user/session customizationrequest/session

πŸ“Œ Summary

  • Spring Boot uses annotations to create and manage objects (beans)

  • By default, each bean is a singleton

  • You can change the scope with @Scope("prototype") and others

  • Spring handles injection, lifecycle, and reuse for you


🧠 Bonus Tip for Interviews

πŸ—£ β€œIn Spring Boot, object creation is driven by annotations and classpath scanning. Beans are typically singletons, but we can switch to prototype or request scope as needed. Spring uses dependency injection and reflection to wire dependencies automatically.”


Happy Learning :) 

 

πŸš€ What Happens When You Start a Spring Boot Project – Step-by-Step

Have you ever wondered what actually happens under the hood when you run a Spring Boot application? It looks simple on the surface, but a lot is going on behind the scenes.

In this post, I’ll walk you through each step in the Spring Boot startup processβ€”from hitting "Run" to handling web requests.


🟒 1. You Hit Run or Execute SpringApplication.run()

Your entry point looks like this:


@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

Here’s what kicks off the magic.


βš™οΈ 2. Spring Boot Creates a SpringApplication Instance

Internally, Spring Boot creates an instance of SpringApplication.


SpringApplication app = new SpringApplication(MyApp.class);

It also sets up:

  • Environment

  • ApplicationContext

  • Banner

  • Listeners

  • Initializers


πŸ—οΈ 3. Environment Is Prepared

Spring Boot prepares the environment by:

  • Loading system properties

  • Reading application.properties or application.yml

  • Setting up profiles (like dev, prod, etc.)

  • Merging environment variables

This is handled by ConfigFileApplicationListener.


πŸ” 4. ApplicationContext Is Created

Depending on the project type, one of the following is created:

  • AnnotationConfigApplicationContext (non-web)

  • AnnotationConfigServletWebServerApplicationContext (web apps)


πŸ”Ž 5. Component Scanning & Bean Definition

Spring Boot uses:

  • @ComponentScan to find @Component, @Service, @Repository, etc.

  • @Configuration to load custom configs

These classes are registered as Spring Beans in the ApplicationContext.


πŸ”§ 6. Auto-Configuration via @EnableAutoConfiguration

Spring Boot checks all entries in:


META-INF/spring.factories

Example:


EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

It loads only the relevant configurations based on classpath dependencies.


🧱 7. Embedded Server (like Tomcat) Starts

If it’s a web project, Spring Boot:

  • Auto-configures Tomcat (or Jetty, Undertow)

  • Registers DispatcherServlet

  • Binds server port (default 8080)

  • Starts the HTTP listener

No need to deploy a WAR file β€” it runs as a standalone JAR!


πŸ”„ 8. ApplicationRunner or CommandLineRunner Executes

If your project has logic like this:


@Component public class MyRunner implements CommandLineRunner { public void run(String... args) { System.out.println("App started!"); } }

Spring Boot will run it after startup.


πŸ–₯️ 9. Application Is Up and Ready!

You’ll see:


Started MyApp in 3.456 seconds Tomcat started on port(s): 8080 (http)

πŸŽ‰ Your app is now live at http://localhost:8080


🌐 10. Request Handling Begins

From now on:

  • DispatcherServlet routes incoming HTTP requests

  • Controllers like @RestController respond to them


@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Spring Boot!"; } }

🧠 Recap: Spring Boot Startup Flow


@SpringBootApplication ↓ SpringApplication.run() ↓ Prepare Environment & Context ↓ Load application.properties ↓ Component Scanning ↓ Auto-Configuration ↓ Start Embedded Server ↓ Initialize Beans ↓ Run ApplicationRunner / CommandLineRunner ↓ App is READY to Handle Requests

Happy Learning :)

 

πŸ” 10 Tricky Spring Boot Internal working Interview Questions You Must Know (with Answers)

Spring Boot makes life easier for developers, but interviewers love to dig into what happens under the hood. If you're preparing for a Spring Boot interview, these tricky questions and answers will give you an edge!


βœ… 1. What exactly happens when you call SpringApplication.run()?

When you invoke SpringApplication.run():

  • It creates and configures the ApplicationContext

  • Loads application.properties or .yml configuration files

  • Registers ApplicationListeners and ApplicationInitializers

  • Performs component scanning

  • Triggers auto-configuration via @EnableAutoConfiguration

Pro Tip: Mention that it uses SpringFactoriesLoader to load configuration classes from META-INF/spring.factories.


βœ… 2. How does Spring Boot decide which configuration class to load automatically?

Spring Boot uses:


SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class)

It loads class names from:


META-INF/spring.factories

Only those relevant to the current classpath dependencies are activated.


βœ… 3. What is the difference between @SpringBootApplication and @EnableAutoConfiguration?

  • @SpringBootApplication is a meta-annotation that includes:

    • @Configuration

    • @ComponentScan

    • @EnableAutoConfiguration

  • Using only @EnableAutoConfiguration will not scan for beans.

πŸ“Œ Tip: Interviewers often test if you understand this convenience wrapper.


βœ… 4. If two auto-configuration classes try to create the same bean, who wins?

Spring Boot uses conditional annotations like:


@ConditionalOnMissingBean

This means:

  • If you define the bean manually β†’ your bean wins

  • Otherwise, Spring uses the auto-configured one

This is how Spring Boot gives you full control to override.


βœ… 5. How is DispatcherServlet registered without a web.xml?

Spring Boot uses auto-configuration:


DispatcherServletAutoConfiguration

Internally, it uses a ServletRegistrationBean to register the DispatcherServlet at runtime β€” no need for web.xml.


βœ… 6. How can you disable a specific auto-configuration?

There are two ways:

a) Using exclude in @SpringBootApplication:


@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })

b) In application.properties:


spring.autoconfigure.exclude=
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

βœ… 7. What if multiple application.properties files are found in the classpath?

Spring Boot loads properties in the following priority order:

  1. /config/application.properties

  2. /application.properties in root classpath

  3. External files via -Dspring.config.location=...

  4. Command-line arguments override all

This enables flexible configuration across environments.


βœ… 8. Can you run a Spring Boot app without @SpringBootApplication?

Yes. Just use the equivalent annotations manually:


@Configuration @EnableAutoConfiguration @ComponentScan

But @SpringBootApplication is the cleaner, preferred approach.


βœ… 9. How does Spring Boot determine if it's a web application?

Spring Boot checks the classpath:

  • If it finds spring-web, spring-webmvc, or ServletContext β†’ it's a web app

  • Then it loads web-specific configurations like:

    • DispatcherServletAutoConfiguration

    • WebMvcAutoConfiguration


βœ… 10. What happens if there is no application.properties or .yml?

Spring Boot still starts using default values, such as:

  • Port: 8080

  • Context path: /

  • Embedded H2 database (if JPA is on classpath)

  • Default error page at /error

But defining properties is essential for production-ready apps

 

How Spring Boot Works Internally – Step-by-Step with Real Example

Spring Boot makes it easy to create stand-alone, production-grade Spring applications with minimal configuration. But what really happens when you run a Spring Boot app?

Let’s break it down step-by-step with code and an easy-to-understand flow.


1. Application Entry Point – @SpringBootApplication


@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
  • @SpringBootApplication is a meta-annotation that includes:

    • @Configuration – Marks this class as a source of bean definitions

    • @EnableAutoConfiguration – Tells Spring Boot to auto-configure beans

    • @ComponentScan – Enables scanning for components (@Component, @Service, etc.)


2. Bootstrapping with SpringApplication.run()

When SpringApplication.run(MyApp.class, args) is called:

  • It creates a SpringApplication instance

  • Prepares the environment and application context

  • Loads application.properties or application.yml

  • Registers listeners and initializers


3. Auto-Configuration Magic

Spring Boot looks into the META-INF/spring.factories file and loads @Configuration classes based on dependencies.

Example:


org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
  • If spring-web is present β†’ WebMvcAutoConfiguration kicks in

  • If spring-boot-starter-data-jpa is present β†’ JPA configurations are loaded


4. Embedded Server Starts Automatically

If it's a web app:

  • Tomcat is auto-configured and started by Spring Boot

  • No need for external WAR deployment


TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

App runs on http://localhost:8080 by default


5. Bean Scanning and Registration

Spring Boot scans for annotations like:

  • @Component

  • @Service

  • @Repository

  • @RestController

And registers them as beans in the ApplicationContext.


6. Request Dispatching with DispatcherServlet

Spring Boot registers DispatcherServlet automatically for web apps.

Example Controller:


@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello from Spring Boot!"; } }

Request to /hello is handled by this method.


7. Application Ready

Once the context is loaded, Spring Boot triggers:

  • CommandLineRunner or ApplicationRunner if present

  • Prints a log like:

    Started MyApp in 3.456 seconds

Quick Example: Complete App


@SpringBootApplication public class BlogDemoApplication { public static void main(String[] args) { SpringApplication.run(BlogDemoApplication.class, args); } } @RestController class DemoController { @GetMapping("/") public String home() { return "Welcome to my blog!"; } }

Run it, and your app is live at http://localhost:8080/


Spring Boot Internals – Summary Flow


@SpringBootApplication ↓ SpringApplication.run() ↓ Load Properties & Beans ↓ Auto-Configuration via spring.factories ↓ Embedded Tomcat/Jetty Starts ↓ Component Scanning & Bean Registration ↓ DispatcherServlet Routes Requests ↓ App is Ready to Serve




Friday, 4 April 2025

Java interview questions on throw and throws 


1️⃣ Can we use throw and throws together in the same method?

βœ… Answer: Yes, we can use both throw and throws in the same method.

πŸ”Ή throws is used in the method signature to indicate that the method may throw an exception.
πŸ”Ή throw is used inside the method to actually throw an exception.

βœ… Example:


public void processPayment(double amount) throws IllegalArgumentException { if (amount <= 0) { throw new IllegalArgumentException("Amount must be greater than zero"); } System.out.println("Processing payment: " + amount); }

πŸ’‘ Trick: Many candidates confuse throw and throws, but remember that throw actually throws the exception, while throws just declares it.


2️⃣ Can a method declare throws but never actually throw an exception?

βœ… Answer: Yes, a method can declare throws even if it does not explicitly throw an exception inside.

βœ… Example:


public void dummyMethod() throws IOException { // No actual exception thrown inside System.out.println("This method declares IOException but does not throw it."); }

πŸ’‘ Trick: Some interviewers use this question to check if you understand that throws is just a declaration and does not enforce throwing an exception inside the method.


3️⃣ What happens if we write throw without specifying an exception?

βœ… Answer: The code will not compile.

πŸ”Ή The throw statement must be followed by an exception object.
πŸ”Ή Java requires an explicit exception object (of type Throwable or its subclasses).

❌ Incorrect Code:


public void testMethod() { throw; // Compilation error: 'throw' must be followed by an exception instance }

βœ… Correct Code:


public void testMethod() { throw new RuntimeException("Something went wrong!"); }

πŸ’‘ Trick: Java does not allow a bare throw statement without an exception object.


4️⃣ Can we throw multiple exceptions using throw?

βœ… Answer: No, throw can only throw one exception at a time.

πŸ”Ή If multiple exceptions need to be thrown, they must be handled in separate conditions or wrapped in a combined exception.

❌ Incorrect Code:


throw new IOException(); throw new SQLException(); // Compilation error: unreachable code

βœ… Correct Code:


public void checkErrors(boolean condition1, boolean condition2) { if (condition1) { throw new IOException("File error"); } else if (condition2) { throw new SQLException("Database error"); } }

πŸ’‘ Trick: Unlike throws, which can declare multiple exceptions, throw can only send one exception at a time.


5️⃣ What happens if we declare a throws clause in main()?

βœ… Answer: The main() method can declare throws, and any unhandled exception will be propagated to the JVM.

βœ… Example:


public static void main(String[] args) throws IOException { readFile("nonexistent.txt"); // Exception not handled, JVM will terminate the program if it occurs } public static void readFile(String filePath) throws IOException { FileReader fr = new FileReader(filePath); // May throw IOException }

πŸ’‘ Trick: If main() has throws Exception, the program may crash unless handled properly using try-catch.


6️⃣ Why should we prefer custom exceptions over generic exceptions in throw?

βœ… Answer: Custom exceptions provide better clarity and help in debugging issues more effectively.

πŸ”Ή Instead of throwing a generic exception like Exception or RuntimeException, we should create our own meaningful exceptions.

βœ… Example:


class InsufficientBalanceException extends Exception { public InsufficientBalanceException(String message) { super(message); } } public void withdraw(double amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Balance is too low!"); } balance -= amount; }

πŸ’‘ Trick: A well-defined exception name (like InsufficientBalanceException) makes debugging much easier than throw new RuntimeException("Something went wrong").


7️⃣ What happens if we throw an exception inside a finally block?

βœ… Answer: If an exception is thrown inside the finally block, it overrides any previous exceptions thrown in try or catch.

βœ… Example:


public void testMethod() { try { throw new IOException("Try block exception"); } catch (Exception e) { System.out.println("Caught: " + e.getMessage()); } finally { throw new RuntimeException("Finally block exception"); // Overrides previous exception } }

Output:


Exception in thread "main" java.lang.RuntimeException: Finally block exception

πŸ’‘ Trick: Any exception in finally will suppress exceptions from try and catch, so avoid throwing exceptions from finally unless necessary.


8️⃣ What happens if a checked exception is thrown but not declared using throws or handled using try-catch?

βœ… Answer: The code will not compile because Java enforces checked exceptions to be either:

  1. Handled using try-catch

  2. Declared using throws

❌ Incorrect Code (Compilation Error):


public void readFile() { FileReader fr = new FileReader("file.txt"); // Compilation error: Unhandled exception }

βœ… Correct Code:


public void readFile() throws IOException { FileReader fr = new FileReader("file.txt"); // No compilation error now }

πŸ’‘ Trick: Java forces you to handle checked exceptions, unlike unchecked exceptions.


9️⃣ Can we override a method and remove throws from the overridden method?

βœ… Answer: Yes, a subclass can remove the throws clause while overriding a method, but it cannot declare new broader exceptions than the superclass.

βœ… Example:


class Parent { public void display() throws IOException { System.out.println("Parent method"); } } class Child extends Parent { @Override public void display() { // Removed 'throws IOException' System.out.println("Child method"); } }

πŸ’‘ Trick: A subclass can handle exceptions internally and remove throws, but it cannot declare new broader exceptions (e.g., Exception instead of IOException).


πŸ”Ÿ Can we use throws with finally?

βœ… Answer: Yes, but the finally block executes before the method exits, even if an exception is thrown.

βœ… Example:


public void riskyMethod() throws IOException { try { throw new IOException("Try block exception"); } finally { System.out.println("Finally block executed"); } }

πŸ’‘ Trick: finally will always execute before the exception propagates to the caller.


πŸ”₯ Quick Recap (for Interviews)

βœ… throw β†’ Actually throws an exception.
βœ… throws β†’ Declares that a method may throw an exception.
βœ… throw requires an exception object.
βœ… throws does not require an objectβ€”just a declaration.
βœ… A method can throws multiple exceptions but can only throw one at a time.
βœ… Exceptions in finally override exceptions from try-catch.