2018-09-22

In this blog post, I am going to explain how to use dependency injection in spring using setter injection and Java configuration. This blog post assumes you already have Java and Maven installed. Step 1: Create a Java Project using Maven Step 2: Let’s create some placeholder folders Step 3: Create the model class src/main/java/com/mycompany/productstore/model/Product.java Step 4: Create a repository interface and its implementation class src/main/java/com/mycompany/productstore/repository/ProductRepository.java src/main/java/com/mycompany/productstore/repository/ProductRepositoryImpl.java Generally, in business applications, the repository implementation class connects to the database. But for the simplicity of this blog post, I am returning some hardcoded values. Step 5: Create a service interface and its implementation class src/main/java/com/mycompany/productstore/service/ProductService.java src/main/java/com/mycompany/productstore/service/ProductServiceImpl.java The ProductServiceImpl class is dependent on ProductRepository object to get the products, instead of creating an object for its implementation class ProductRepositoryImpl we created a setter for ProductRepository interface. In the next steps, we use spring dependency injection to inject the object of ProductRepositoryImpl into ProductService class using setter method of ProductRepository interface at runtime. Step 6: Add the spring (spring-context) to our project in the pom.xml file The spring-context jar is enough to use the dependency injection. Step 7: Let’s a AppConfig.java file to create the beans configuration using Java src/main/java/com/mycompany/productstore/AppConfig.java In the above bean configuration first, we annotated the AppConfig class (it is replacing the XML configuration) using spring @Configuration annotation. Next, we created ProductRepositoryImpl bean and using getProductRepository() method, and annotated it with spring @Bean annotation. Finally, we created ProductServiceImpl bean using getProductService() method and annotated it with spring @Bean annotation. As ProductServiceImpl class dependent on ProductRepositoryImpl object, we passed it as dependency using setProductRepository() setter method. The @Configuration annotation indicates that the Spring IoC container can use the class as a source of bean definitions. The @Bean annotation indicates method will return an object that should be registered as a bean...

Show more