Skip to content

CT Autowired

kapilkalra04 edited this page Feb 18, 2018 · 6 revisions

Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection. Note that Autowiring can't be used to inject primitive and string values (POJO). It works with references only, ie anything that is not a POJO. Autowiring is used to make the code more decoupled and more testable. The @Autowired annotation on a field tells the Spring IoC Contatiner to look for equivalent beans for that field and inject them when an object of the class is created. This allows us to not worry about the class' dependencies on other classes.

For learning the basics of Autowiring in Spring, refer the links below :

  1. https://www.youtube.com/watch?v=suiEGbKf21g (Basic Spring Tutorial for contributors new to Spring framework).
  2. http://www.baeldung.com/spring-autowire (Exhaustive list of all variations/features of @Autowired annotation).

Example usage of the @Autowired annotation in BITS-Darshini can be found using the links given below :

  1. PerformanceMetricsTest.java

(Observe the interaction of @ContextConfiguration annotation and @Autowired annotation. @ContextConfiguration lets Spring know where to search for definitions of beans marked by @Autowired annotation for testing purposes. Here, it points to PerformanceMetricsConfig.java, which is a config class containing all required bean definitions.)

  1. SaveRepository.java

NOTE :

Many of the tutorials found online teach Spring Autowiring using XML-based configuration. This project uses the Java equivalent of the same, which has java annotations and gives better readability of code.

Clone this wiki locally