We use bean mainly to achive loose coupling.
When you are creating objects by yourself, then these objects are tight coupled.
Imagine an application with dozens or even hundreds of classes. Sometimes we want to share a single instance of a class across the whole application, other times we need a separate object for each use case, and so on.
Managing such a number of objects is nothing short of a nightmare. This is where inversion of control comes to the rescue.
Instead of constructing dependencies by itself, an object can retrieve its dependencies from an IoC container. All we need to do is to provide the container with appropriate configuration metadata.
With the IOC, you can achieve loose coupling.
Loose coupling means that classes are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/P model and through dependency injection its possible to achieve loose coupling.
Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.
Java program to illustrate loose coupling concept
public interface Topic
{
void understand();
}
class Topic1 implements Topic {
public void understand()
{
System.out.println("Got it");
}
} class Topic2 implements Topic {
public void understand()
{
System.out.println("understand");
}
} public class Subject {
public static void main(String[] args)
{
Topic t = new Topic1();
t.understand();
}
}
Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.
Hope it helps.