Dependency Injection in Spring | PLM Developer

Spring is open-source and easy to use Java MVC Framework used by millions of developers around the world. Spring is a lightweight, easy to test, and loose coupling framework.

Dependency Injection:

Dependency Injection allows the java classes to be as independent as possible of other classes. This feature will reduce the dependency on the other classes. So, it is easy to maintain and test the application.

There are two ways to inject dependency:
  1. By Constructor parameter
  2. By setter method


Let us see the dependency with example:


public class ClassA {
ClassB classB;

    public void doSomething() {
        classB.getInfo();
    }
}

public class ClassB {
    public String getInfo() {
       return "ClassB Info";
    }
}

From the above example, ClassA is dependent on ClassB, and ClassB is called dependency of ClassA. This type of dependency referred to as hard-coded dependency. This code looks more straightforward, but in real-life applications are complicated, and many dependencies among the classes lead to some drawbacks.

In Spring annotations like @Autowired, the container asked to inject a dependency where it is needed, and the programmers do not need to take off create or manage dependencies.

Post a Comment

0 Comments