Spring - Dependency Injection

springmvc

@Service        // Indicate that this class is a service component.  Spring will
                // create instance of this service component and inject it into the place
                // where the @Autowired annotation is used 

@Autowired      // Tell Spring to inject appropriate service here:
                // @Autowired
                // private LoginService loginService;
                // Spring will automatically create an instance of the LoginService

@Component      // This is like the @Service annotation

A service is a Java class marked with the @Service annotation:

@Service
public class LoginService {
    public boolean validateUser(String user, String password) {
        return user.equalsIgnoreCase("whatever") && password.equals("dummy");
    }
}

To use dependency injection, first we need to define a service or component:

import org.springframework.stereotype.Component;

@Component
public class GoodMorningServiceImpl implements HiService {
  public String sayHi() {
    return "Good Morning";
  }
}

And then we have to use the component (by using the @Autowired annotation):

@Configuration
@ComponentScan(basePackages = "com.in28minutes.example.spring.business.examples")
class JavaTestContext {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JavaTestContext.class);
public class DependencyInjectionJavaContextExamples {
  @Autowired
  private HiService service;

  @Test
  public void dummyTest() {
  }
}

Whenever, Spring see the @Autowired annotation, it will create the component and inject that component into the code.

To create a JUnit test case to be run with the Spring Context, use the @RunWith(SpringJUnit4ClassRunner.class) annotation:

import org.springframework.stereotype.Component;

@Component
public class GoodMorningServiceImpl implements HiService {
  public String sayHi() {
    return "Good Morning";
  }
}

@Configuration
@ComponentScan(basePackages = "com.in28minutes.example.spring.business.examples")
class JavaTestContext {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JavaTestContext.class);
public class DependencyInjectionJavaContextExamples {
  @Autowired
  private HiService service;

  @Test
  public void dummyTest() {
  }
}

What are the annotations used for dependency injection?

@Component
@ComponentScan(basePackages = "com.in28minutes.example.spring.business.examples")

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JavaTestContext.class)

@Autowired
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License