Software Development

Autowire beans to a List in Spring using Java


Udemy

This post is about how to auto-wire a set of beans to a list in Spring. Essentially, we need to add @bean‘s to an list.

In vanilla Java, we’ll do something like:

Requirements

Stuff used in this post.

  • IntelliJ IDEA Ultimate 2016.3
    • Built-in Spring Initialzr will be used. Alternatively, start.spring.io can be used.
  • Spring Boot 1.5.4.RELEASE
  • Java 8
  • Windows 10 Enterprise

New Maven Project

[wp_ad_camp_1]

Use Spring Initilzr to generate a template Maven project that contains, importantly, the minimum dependencies required to get the application running. This can be done via the built-in Spring Initilzr in IntelliJ or via start.spring.io

In IntelliJ

Basic project information for Maven

Select nothing. Click Next.

Spring Initlzr – web

Generate application via https://start.spring.io/

Generated pom.xml

[wp_ad_camp_2]

This is the pom.xml generated from the Spring Initilzr. There’s no need to modify this and we can immediately concentrate on writing our codes.

Java Codes

In SpringBoot, all components get @ComponentScan‘d automatically when they are located in the same package (including subpackages) as the class that is annotated with @SpringBootApplication.

Therefore, our codes are in the same package as ComTurretaSpringAutowiretolistApplication

All components are in the same package as the main class

 

ComTurretaSpringAutowiretolistApplication

This is our main class and Spring Boot application.

DepartmentBean

This class represents a Department in a company. A department may contain on or more employees (persons). It is annotated with @Component to allow Spring to instantiate it. Note we have a list field annotated with @Autowired. We need the next 2 classes.

[wp_ad_camp_4]

PersonBean

This class represents are person (or employee) assign to a department in a company. Nothing special about it. It’s just a POJO. It is not annotated with anything though. We’ll create instances of this class using the next Java class.

CustomConfiguration

This class is annotated with @Configuration that will enable us to create several instance of PersonBean using @Bean. The @Order indicates the order which the beans are created and added to the list in the DepartmentBean object.

In the DepartmentBean object, person 1 appears before person 2 and so on.

[wp_ad_camp_5]

Testing

To test our codes within IntelliJ, simply run ComTurretaSpringAutowiretolistApplication.

Download the Codes

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like