4

What exactly is the advantages of autowiring is Spring?

An example of autowiring in spring would be like

public class TestClass {
    testMethod() {
        // .....
    };
}

public class MainClass {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClasspathXmlApplicationContext("test.xml");
        TestMethod obj = (TestClass) ctx.getBean("test");
        obj.testMethod();
    }
}

test.xml

<bean id="test" class="TestClass">

same in a normal operation could be done using:

public class MainClass {
    public static void main(String[] args) {
        TestClass obj = new TestClass();
        obj.testMethod();
    } 
}

What is the advantage of Spring, I mean I have heard about terms Inversion of control and Dependency Injection. In both the examples a reference of TestClass is used once through Spring XML again through new oerator. So can someone in simple terms explain what is the advantage.

kryger
  • 12,906
  • 8
  • 44
  • 65
Amit Saha
  • 61
  • 3
  • 8
  • 1
    If your application consists of a single class with a single method, dependency injection is not useful, because you have 0 dependency to inject. It becomes useful when you have components depending on other components, depending on other components. Like in a typical web app, where UI constrollers depend on business services, which depend on other services and DAOs. – JB Nizet May 02 '13 at 20:04

1 Answers1

5

Spring is taking care of creating of the objects. Let's say in spring boot you are creating a service:

@Service
public class CreditService { ....

with this you are saying to spring boot that he needs to create an object from type CreditService and whenever you want to use it you don't need to create it you can just say:

@Autowired
private CreditService creditService;

With that you are getting an reference: creditService , that will point to the object that spring boot created for you and call the methods (services). So basically spring is taking care of creation of the object and you are just calling it, not to worry about creating new object anywhere.

f.trajkovski
  • 794
  • 9
  • 24