0
0
Spring Bootframework~5 mins

Bean concept in Spring in Spring Boot

Choose your learning style9 modes available
Introduction

A bean in Spring is an object that Spring manages for you. It helps organize and reuse parts of your app easily.

When you want Spring to create and manage objects automatically.
When you need to share the same object across different parts of your app.
When you want to separate configuration from your business logic.
When you want Spring to handle object lifecycle like creation and destruction.
When you want to use dependency injection to connect parts of your app.
Syntax
Spring Boot
@Component
public class MyBean {
    // your code here
}

// or

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

@Component tells Spring to create and manage this class as a bean automatically.

@Bean is used inside a configuration class to define a bean manually.

Examples
This marks UserService as a bean that Spring will create and manage.
Spring Boot
@Component
public class UserService {
    // business logic
}
This defines a bean manually inside a configuration class.
Spring Boot
@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}
This injects the UserService bean into another class automatically.
Spring Boot
@Autowired
private UserService userService;
Sample Program

This Spring Boot app defines a GreetingService bean with @Component. It injects it into the main app class using @Autowired. When run, it prints a greeting message from the bean.

Spring Boot
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Component
class GreetingService {
    public String greet() {
        return "Hello from Spring Bean!";
    }
}

@SpringBootApplication
public class BeanExampleApp implements CommandLineRunner {

    @Autowired
    private GreetingService greetingService;

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

    @Override
    public void run(String... args) throws Exception {
        System.out.println(greetingService.greet());
    }
}
OutputSuccess
Important Notes

Beans are single instances by default (singleton scope) unless configured otherwise.

Use @ComponentScan or @SpringBootApplication to tell Spring where to find beans.

Beans help keep your code clean by separating creation and usage.

Summary

Beans are objects managed by Spring to help organize your app.

You create beans using @Component or @Bean annotations.

Spring injects beans where needed to connect your app parts easily.