Spring MVC

🫘 What is a Bean?

Think of a Bean as an object (a real Java class) that Spring takes care of for you.


🧠 Simple Analogy:

Imagine you own a coffee shop.

  • Normally, you’d hire the staff, buy the coffee machine, buy the cups—you do everything yourself.

  • But in the Spring world, it’s like you have a manager (Spring Container) who says:


    “Tell me what you need, and I’ll arrange everything for you. You just sit back and enjoy.”


So if your application needs a class like CoffeeMaker, Spring will:

  • Create an object of it (i.e., a Bean),

  • Give it everything it needs to work (like water, coffee powder, cups—called dependencies),

  • And give you the ready-to-use CoffeeMaker.


🔄 What is Inversion of Control (IoC)?

It literally means: You don’t control how things are created anymore—Spring does.

In traditional code:

CoffeeMaker cm = new CoffeeMaker(new Filter(), new Grinder());


➡️ You are in control. You create the object and its parts.

But in IoC:

@Autowired

CoffeeMaker cm;


➡️ You just say, "I need a CoffeeMaker", and Spring gives it to you fully set up.


🧪 What is Dependency Injection (DI)?

It’s how Spring gives you what you need.

Example: If your CoffeeMaker needs a Filter, Spring will inject a Filter object into it automatically.


🔁 Summary in Simple Words

Concept

Everyday Example

Bean

A prepared item (e.g., CoffeeMaker) you can use

IoC

Letting the coffee shop manager do the setup

Dependency

Filter, Grinder — things the CoffeeMaker needs

Dependency Injection

Manager giving those parts while preparing the CoffeeMaker




✅ What Are Annotations?

In simple words:

Annotations are special tags in Java (starting with @) that give extra information to the Java compiler or Spring framework about how to treat your code.

Example:

@Autowired


This tells Spring: “Please inject a dependency here.”


🧠 Real-life Analogy

Think of annotations like sticky notes on your objects:

@Component"Hey Spring, manage this as a bean!"
@Autowired"I need help, give me the required part automatically!"
@Service"This class does business logic -- treat it accordingly."
@Repository"This class talks to the database."
@Controller"This class handles web requests."




🎯 Basic Spring Annotations for Bean Management

Annotation

Use Case

@Component

Declares a generic bean

@Service

Declares a business logic bean

@Repository

Declares a database access bean

@Controller

Declares a web layer bean

@Autowired

Automatically injects dependencies


🔧 Full Example using Annotations

Let’s use the coffee shop analogy again but now with annotations.


1️⃣ Dependency: Filter.java

import org.springframework.stereotype.Component;


@Component
public class Filter {
    public String getFilterType() {
        return "Steel Filter";
    }
}


Here, @Component tells Spring to create and manage a Bean of Filter.


2️⃣ Main Bean: CoffeeMaker.java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


@Component
public class CoffeeMaker {

    private Filter filter;

    // Constructor injection (recommended)
    @Autowired
    public CoffeeMaker(Filter filter) {
        this.filter = filter;
    }

    public void brew() {
        System.out.println("Brewing coffee using: " + filter.getFilterType());
    }
}


  • @Component = Make this a Bean

  • @Autowired = Spring, please give me the Filter


3️⃣ Main App: MainApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example")  // Adjust package if needed
public class MainApp {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainApp.class);

        CoffeeMaker coffeeMaker = context.getBean(CoffeeMaker.class);
        coffeeMaker.brew();
    }
}



✅ Output

Brewing coffee using: Steel Filter



🚀 Recap

Concept

Annotation Used

Role

Make it a bean

@Component

Tells Spring to manage this class

Inject dependency

@Autowired

Tells Spring to "give me this dependency"

Auto-discovery

@ComponentScan

Tells Spring to scan the package for beans

App configuration

@Configuration

Tells Spring that this is a config class


🧱 What is "Scope"?

In real life, scope means how long something lives and who gets to use it.

In Spring, scope means:

"How many copies of an object do you want Spring to create and who should get it?"

Spring manages Java objects (called Beans) and gives them to you when needed. But you can tell Spring how to manage those objects using scopes.


🧠 Real-Life Examples for Each Scope

1️⃣ singleton — Default

🧍‍♂️ One shared object for everyone.

Like one printer in an office — everyone uses the same one.

  • Spring creates one CoffeeMaker, and everyone shares it.

  • Fast and memory-saving.

🧪 Example:

@Scope("singleton")  // (or omit, since it's default)



2️⃣ prototype — New every time

🎁 One new object every time you ask.

Like using a new paper cup every time you drink coffee.

  • Spring creates a new CoffeeMaker every time someone asks.

  • Useful when objects need to be independent or carry different data.

🧪 Example:

@Scope("prototype")



3️⃣ request — One per web request

🌐 One object per HTTP request.

Like a shopping cart that exists only while you’re browsing a website. Once done, it disappears.

  • Spring gives one CoffeeMaker per web request, and it's gone after that.

🧪 Example:

@Scope("request")


(Used only in web apps)


4️⃣ session — One per user login session

🔐 One object per user session.

Like a Netflix account — it remembers what you're watching until you log out.

  • Spring creates one CoffeeMaker per user, and it stays until the user logs out or session ends.

🧪 Example:

@Scope("session")


(Used in web apps only)


5️⃣ globalSession — Legacy scope

🏛️ Like a shared lobby for everyone in a government building.

  • Mostly used in old-style portals (you won’t need this in most apps).

  • Ignore unless you're doing advanced/legacy work.

🧪 Example:

@Scope("globalSession")



🗂️ Summary Table (in Lehman’s terms)

Scope

Who Gets the Object?

Lives Until...

Real-life Example

singleton

Everyone shares the same

Application is running

Office Printer

prototype

Everyone gets a fresh copy

Immediately thrown after use

Disposable Paper Cup

request

One per web request

Request ends

Shopping Cart for 1 visit

session

One per user

User logs out / session ends

Netflix account

globalSession

One per portal

Global session ends

Shared lobby in a portal


🔧 How to Tell Spring About Scope?

Just add @Scope("...") on your class like this:

@Component
@Scope("prototype"// or singleton / request / session
public class CoffeeMaker {
    // ...
}

Note: @Scope can be added for @Bean@Component@Service@Controller@RestController, etc.



What is @SpringBootApplication?

It's a shortcut annotation that tells Spring Boot:

“Hey! This is the starting point of my application. Please auto-configure everything for me.”


📦 Full Definition

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan


So when you write:

@SpringBootApplication
public class MyApp { ... }


It secretly means you're using three annotations at once.


🧠 Lehman’s Analogy

Imagine you’re opening a restaurant.

  • @Configuration = Your kitchen blueprint (how things are laid out)

  • @ComponentScan = Your hiring manager, who finds all your staff (classes with @Component, @Service, etc.)

  • @EnableAutoConfiguration = Your smart assistant, who says:


    "Oh, you added a coffee machine? I’ll automatically plug it in and set it up!"


Together, @SpringBootApplication = A restaurant manager who knows:

  1. What kitchen setup to use (@Configuration)

  2. Who the staff is (@ComponentScan)

  3. How to auto-setup things (@EnableAutoConfiguration)


🧱 Let’s Break it Down Step by Step

✅ 1. @Configuration

“This class contains instructions on how to create beans manually if needed.”

Example:

@Configuration
public class AppConfig {
    @Bean
    public CoffeeMaker coffeeMaker() {
        return new CoffeeMaker();
    }
}


💡 Without this, Spring won't know how to create things you manually define.


✅ 2. @EnableAutoConfiguration

“Spring, look at my classpath and automatically configure things based on what you find.”

Example:

  • If Spring sees H2 Database in your project:
    ✅ It auto-configures an H2 connection.

  • If you add Spring Web:
    ✅ It auto-creates an embedded Tomcat server.

💡 This is what gives Spring Boot its magic — no XML, no manual setup!


✅ 3. @ComponentScan

“Look for all the Java classes in this package and its sub-packages that have annotations like @Component, @Service, @RestController, etc., and register them as beans.”

Without this, your @Component classes won’t be discovered.


✅ Final Example in Lehman's Code

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


When you run this:

🧰 Spring does 5 things:

  1. Sees @SpringBootApplication → understands this is the main entry point.

  2. Applies @Configuration → loads any manual beans if present.

  3. Applies @ComponentScan → finds all classes with @Component, @Service, etc.

  4. Applies @EnableAutoConfiguration → configures beans automatically (like database, web server).

  5. Starts the embedded Tomcat server (if it's a web app).


🧾 Summary in Lehman's Table

Annotation

Job

Real-Life Analogy

@Configuration

Says "This class gives bean instructions"

Kitchen setup

@EnableAutoConfiguration

Spring auto-detects and configures beans

Smart assistant setting up appliances

@ComponentScan

Finds and registers your classes (beans)

Hiring all employees

@SpringBootApplication

Combines all the above to auto-start your app

Restaurant manager




🏷️ What is @Bean in Lehman's Terms?

@Bean means:

“Hey Spring, I want you to create and manage this object manually, even though it's not marked with @Component, @Service, etc.”

It’s like saying:

“This object is not from your usual hiring system (@ComponentScan). I’m bringing in an outside helper manually, so please manage it for me.”


🧠 Real-Life Analogy

Imagine your restaurant (Spring app) needs an external delivery guy (like Swiggy). He’s not your staff, but you still need him to bring coffee beans regularly.

  • You manually bring him in.

  • You want your manager (Spring) to still track and manage him.

This is where you say:

@Bean
public DeliveryGuy deliveryGuy() {
    return new DeliveryGuy("Swiggy");
}


So now Spring knows:
➡️ “Ah! I need to manage this guy like I do for internal staff!”


💡 When is @Bean used in Spring MVC?

In Spring MVC, it's commonly used to manually create things like:

  • RestTemplate (for making HTTP API calls)

  • ModelMapper (for converting between DTOs and entities)

  • ObjectMapper (for custom JSON handling)

  • Custom ViewResolvers, Interceptors, Filters, etc.


✅ Common Use Case: RestTemplate Bean

⚙️ Why we need it:

Spring doesn’t provide RestTemplate automatically. You have to create it manually and let Spring manage it.


✅ Example Code (Step by Step)


1️⃣ Create the Bean Using @Bean

// AppConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

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


🧠 Explanation:

  • @Configuration tells Spring this class provides setup instructions.

  • @Bean tells Spring: "Please create and manage this RestTemplate instance."


2️⃣ Use That Bean in a Controller

// CoffeeController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CoffeeController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/external-coffee")
    public String getExternalCoffee() {
        String apiUrl = "https://api.sampleapis.com/coffee/hot";
        return restTemplate.getForObject(apiUrl, String.class);
    }
}


🧠 What happens here:

  • You ask Spring for a RestTemplate.

  • Spring says: “Ah, I already have that! I built it from @Bean config.”

  • Spring injects it into your controller like it does for @Service or @Repository.


🔁 What if I didn’t use @Bean?

You’d have to write:

RestTemplate restTemplate = new RestTemplate();


But this breaks Spring’s model — you’re doing manual work everywhere, losing benefits like:

  • Auto-injection

  • Centralized configuration

  • Custom settings (like timeouts or interceptors)


🔍 Summary Table

Concept

Lehman’s Term

Why Important

@Bean

Manual object builder (outside staff)

You define how the object is made

@Configuration

Recipe book

Tells Spring: “Beans are declared here”

RestTemplate

Coffee Delivery Boy

Used for calling other REST APIs

Without @Bean

No coffee delivery

You’d have to build objects manually


🧪 Output (Example)

If you visit http://localhost:8080/external-coffee, it will:

  • Use the RestTemplate Bean

  • Call an external API (https://api.sampleapis.com/coffee/hot)

  • Return the JSON response to your browser.

🔧 What is @Autowired in Spring?

@Autowired tells Spring:

"Hey Spring, please give me the object I need — don’t make me create it manually!"

It’s part of Dependency Injection, where Spring automatically gives you the right helper/tool/object (bean) your class needs.


🧠 Real-Life Analogy

Imagine you're a restaurant chef. You don’t buy vegetables, knives, or ingredients yourself.

You say:

“Give me a knife, give me onions.”

And your manager (Spring) makes sure they’re there when you need them.
That’s what @Autowired does — it auto-delivers dependencies to your code.


💡 Where Can You Use @Autowired?

Place

Meaning

On field

Injects the object directly into the field

On constructor

Injects when the object is being created

On setter

Injects via a setter method

On config method

Injects into a @Bean method


✅ Step-by-Step Example (Field, Constructor, Setter)

Let’s build a simple app where a CoffeeMachine needs a Filter.


1️⃣ Create the Dependency Bean

// Filter.java

import org.springframework.stereotype.Component;

@Component
public class Filter {
    public String getFilterType() {
        return "Steel Filter";
    }
}


📌 @Component tells Spring: “Create a Filter bean.”


2️⃣ Field Injection (@Autowired on field)

// CoffeeMachine.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CoffeeMachine {

    @Autowired
    private Filter filter;

    public void brew() {
        System.out.println("Brewing coffee with: " + filter.getFilterType());
    }
}


🧠 Here:

  • Spring looks for a Filter bean.

  • Injects it into the filter field — no need to create it manually.


3️⃣ Constructor Injection (Recommended Way)

// CoffeeMachine.java

@Component
public class CoffeeMachine {

    private final Filter filter;

    @Autowired  // optional in newer Spring versions
    public CoffeeMachine(Filter filter) {
        this.filter = filter;
    }

    public void brew() {
        System.out.println("Brewing coffee with: " + filter.getFilterType());
    }
}


Why is this best practice?

  • Works well with final fields.

  • Encourages immutability.

  • Easy to test.


4️⃣ Setter Injection

@Component
public class CoffeeMachine {

    private Filter filter;

    @Autowired
    public void setFilter(Filter filter) {
        this.filter = filter;
    }

    public void brew() {
        System.out.println("Brewing coffee with: " + filter.getFilterType());
    }
}


📌 Used when the dependency is optional or can change.


5️⃣ Main Application

@SpringBootApplication
public class CoffeeApp {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(CoffeeApp.class, args);

        CoffeeMachine cm = context.getBean(CoffeeMachine.class);
        cm.brew();
    }
}



🧪 Output

Brewing coffee with: Steel Filter


✅ Spring automatically injected the Filter into CoffeeMachine using @Autowired.


📝 Summary Table

Injection Type

Syntax Example

Use Case

Field Injection

@Autowired private Filter filter;

Simple, fast — but harder to test

Constructor

@Autowired public CoffeeMachine(Filter)

✅ Best practice, testable, immutable

Setter

@Autowired public void setFilter(...)

When optional or changeable dependencies


❗ Common Pitfalls to Avoid

Mistake

Fix

No @Component on class to inject

Add @Component, @Service, etc.

Multiple beans of same type

Use @Qualifier("beanName")

Field is private without injection

Use @Autowired or constructor



🧠 What Problem Does @Qualifier Solve?

Imagine you have two similar things (e.g., two types of bikes: Hero and Honda), and you ask Spring:

“Hey Spring, give me a bike.”

Spring will get confused because it sees two bikes and won’t know which one you want. That’s where @Qualifier helps — it lets you specify the name of the bean you want.


✅ Step-by-Step Example

📌 Use Case: Two different database connections (dummy examples)

Let’s simulate 2 DB connections: mysqlDataSource and postgresDataSource.


👣 Step 1: Create a DataSource Interface (or any type you want to inject)

public interface DataSource {

    void connect();

}



👣 Step 2: Create Two Implementations

@Component("mysqlDataSource")
public class MySQLDataSource implements DataSource {
    public void connect() {
        System.out.println("Connecting to MySQL Database...");
    }
}

@Component("postgresDataSource")
public class PostgresDataSource implements DataSource {
    public void connect() {
        System.out.println("Connecting to PostgreSQL Database...");
    }
}


Here, both classes implement DataSource, and are annotated with @Component, but given different names using @Component("name").


👣 Step 3: Inject Specific Bean Using @Qualifier

@Component
public class DatabaseManager {

    private final DataSource dataSource;

    @Autowired
    public DatabaseManager(@Qualifier("postgresDataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void performConnection() {
        dataSource.connect();
    }
}



👣 Step 4: Run the Spring Boot Application

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

        DatabaseManager manager = context.getBean(DatabaseManager.class);
        manager.performConnection();  // Output: Connecting to PostgreSQL Database...
    }
}



🧩 Why @Qualifier is Important?

If you skip @Qualifier like this:

@Autowired

private DataSource dataSource;


Spring will throw an error like:

"No unique bean of type DataSource" – because it found two implementations and doesn’t know which one to inject.


✅ Summary

Concept

In Simple Words

@Autowired

Tells Spring to inject a dependency

Multiple Beans

Spring gets confused if multiple candidates

@Qualifier

Tells Spring which one to use by name


✅ Alternate: With Setter Injection

@Component
public class DatabaseManager {

    private DataSource dataSource;

    @Autowired
    @Qualifier("mysqlDataSource")
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void performConnection() {
        dataSource.connect();
    }
}


1. @Component — General Worker

💡 In Lehman’s Term:

"@Component is a general-purpose worker. You mark a class with this so Spring knows: 'Hey, create and manage this class object for me!'"

✅ Example:

@Component
public class EmailService {
    public void sendEmail(String msg) {
        System.out.println("Sending email: " + msg);
    }
}


Spring will now automatically create and manage this class as a bean.


🛠️ Specialized @Component Types

These are specific job roles (just like in an office, not all employees do the same job):


🧩 2. @Service — Business Logic Guy

💡 In Lehman’s Term:

"@Service is used when your class is handling core business logic, like calculations, processing rules, etc."

✅ Example:

@Service
public class PaymentService {
    public void processPayment() {
        System.out.println("Processing payment...");
    }
}



🧩 3. @Repository — Database Worker (DAO)

💡 In Lehman’s Term:

"@Repository is a worker who talks to the database – for storing, retrieving, updating, deleting data."

✅ Example:

@Repository
public class StudentRepository {
    public void save(Student student) {
        System.out.println("Saving student to DB...");
    }
}


🔧 Also, Spring handles exceptions automatically in these classes (converts SQL exceptions into Spring exceptions).


🧩 4. @Controller — Web Gatekeeper

💡 In Lehman’s Term:

"@Controller handles web requests. It's the guy at the front desk who receives your HTTP requests and sends back the appropriate view (like HTML page)."

✅ Example:

@Controller
public class HomeController {
    @GetMapping("/")
    public String homePage() {
        return "home"; // Returns a view name (e.g., home.html or home.jsp)
    }
}



🧩 5. @RestController — API Responder (JSON guy)

💡 In Lehman’s Term:

"@RestController is like @Controller, but instead of giving HTML pages, it gives back JSON or raw data."

It’s used when building REST APIs.

✅ Example:

@RestController
public class UserAPI {
    @GetMapping("/user")
    public String getUser() {
        return "John Doe"// Returned as raw response body
    }
}


This is the same as:

@Controller
public class UserAPI {
    @GetMapping("/user")
    @ResponseBody
    public String getUser() {
        return "John Doe";
    }
}



🧩 6. @Configuration — Blueprint Maker

💡 In Lehman’s Term:

"@Configuration is used for configuration or setup classes. It's like the architect or blueprint writer of the system."

You often combine it with @Bean methods to create and control beans manually.

✅ Example:

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



🧠 Summary Table

Annotation

Role in Lehman’s Terms

Use Case

@Component

Generic worker

Any class managed by Spring

@Service

Business logic handler

Services, processing

@Repository

Database handler (DAO)

Data access, CRUD

@Controller

Front desk for HTML pages

Handles web pages (MVC)

@RestController

Front desk for APIs (returns JSON/data)

REST APIs

@Configuration

Blueprint/config maker

Configuration classes












Distributed by Gooyaabi Templates | Designed by OddThemes