August 01, 2017

How dependency Injection is achieved in Spring M V C

How dependency Injection is achieved in Spring M V C




Spring will search for two annotations @autowired and @component to do this job. Inversion of control is easily achievable in spring.

A sample program is given below

public class DependencyInjectionEx{

@Autowired
TestSerivceInf service;


@Test
public void TestFun(){
System.out.println(service.callService());

}

}


The Service class that implemented the interface

@Component
Class TestServiceImpl implements TestSerivceInf {

@Override
public String callService(){
    return "consumerfed liquor shop kozhikode";
}

}


The Interface

public interface TestSerivceInf {

    public String callService()

}

Then if more than two servcieimpl class implements an interface, then we need to specify to which class we are autowiring it, Then only springs component scan will works.

One way to create Object as same name as the class.

@Autowired
TestSerivceInf testServiceImpl ; will search for TestServiceImpl class

The second way is @qualifier(value = "className")

@Autowired
@qualifier(value = "TestServiceImpl")
TestSerivceInf testServiceImpl


if you think this tutorial is really helpful let us know.

Facebook comments