Alright, let’s get into what a “Bean” is in Spring Framework!
So, in Spring, a Bean is basically any object that Spring manages for you. It’s like saying, “Hey, Spring, I need this object in my app. Can you take care of it for me?” And Spring’s like, “No problem, I’ll handle it.”What Beans Do
When you declare something as a Bean, Spring keeps track of it, makes sure it's available when needed, and even sets it up with other objects it might depend on (called dependencies). So, if you think of your app as a big Lego build, Beans are the pieces, and Spring figures out how they all fit together.
How to Make a Bean
You can tell Spring to create a Bean in a few ways. The most common is with the @Bean annotation inside a @Configuration class. You might have something like this:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
This tells Spring, “I want a MyService Bean available in my app,” and then Spring goes ahead and makes it.
Or Use @
ComponentAnother way is with the @
Component annotation, which is like saying, "Hey, Spring, any time you scan my project and see this, turn it into a Bean automatically." It’s even more hands-off.
Why Beans Matter- Singleton by Default: Spring makes only one instance of each Bean by default (singleton), which keeps things efficient.
- Dependency Injection: Beans work hand-in-hand with @Autowired, so Spring hooks up the dependencies automatically.
- Loose Coupling: You don’t need to know how each object connects; Spring handles all that setup.
Quick RecapA Bean is just an object managed by Spring. You define it, Spring creates it and wires it up with everything else. It’s like having a personal assistant for your objects, and it keeps your app clean, organized, and super easy to scale.
image quote pre code