Spring Beans and @Bean — Spring Technical Interview Questions & Answers
Objects managed by the Spring IoC container.
Spring Beans and @Bean
- A Spring bean is an object created and managed by the Spring container.
- Spring creates it, injects dependencies, and can destroy it cleanly later.
- Register with @Component/@Service/@Repository or with @Bean in @Configuration.
- Default scope is singleton: one shared instance in the container.
- Thinking every Java object is automatically a bean — only registered ones are.
- Bean = container-managed object.
Technical Interview Tip: Define bean, then name two ways to register one.
Code Examples for Spring Beans and @Bean
Spring Beans and @Bean — working example
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Service
class GreetingService {
String greet(String name) {
return "Hello, " + name;
}
}
@RestController
@RequiredArgsConstructor // constructor injection of final fields
class GreetingController {
private final GreetingService greetings;
@GetMapping("/greet")
String greet() {
return greetings.greet("Spring");
}
}
// Without Lombok — same idea:
// GreetingController(GreetingService greetings) { this.greetings = greetings; }Spring Beans and @Bean — spring injects beans; prefer constructor injection (@RequiredArgsConstructor or explicit ctor) over field @Autowired.
How to Explain Spring Beans and @Bean to an Interviewer
What is Beans and @Bean (sb)?
Used for a short Beans and @Bean sb example a small REST app Not just the heading
Give one small example of Beans and @Bean (sb).
the smallest Beans and @Bean sb example you can type Objects managed by the Spring IoC container
What mistake do beginners make with Beans and @Bean (sb)?
only saying “Beans and @Bean sb” with no example Show the fix
Where do you use Beans and @Bean (sb)?
a small REST app a short Beans and @Bean sb example