Directory Structure
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.4.3
com.example
BeanExample
0.0.1-SNAPSHOT
BeanExample
Demo project for Spring Boot
17
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
📌 @bean Annotation Example in Spring Boot
The @bean annotation in Spring Boot is used to define a bean manually inside a @Configuration class. It tells Spring to manage an instance of the object and inject it wherever needed.
🔹 Example 1: Basic @bean Usage
✔ Scenario: You want to create and manage a HelloService bean manually instead of using @Component.
🚀 Implementation
Step 1: Create a Service Class
public class HelloService {
public String sayHello() {
return "Hello, Spring Boot!";
}
}
Step 2: Define Bean in a @Configuration Class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public HelloService helloService() {
return new HelloService();
}
}
Step 3: Use the Bean in a Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
private final HelloService helloService;
public HelloController(HelloService helloService) {
this.helloService = helloService;
}
@GetMapping
public String sayHello() {
return helloService.sayHello();
}
}
🌟 Expected Output
GET /hello --> Response: "Hello, Spring Boot!"
🛠 When to Use @bean?
✅ When you need fine-grained control over bean creation.
✅ When the class does not use @Component, @Service, or @Repository.
✅ When you want to configure third-party libraries (e.g., RestTemplate, DataSource).