Explain Codes LogoExplain Codes Logo

How to define a List bean in Spring?

java
bean-definition
spring-config
list-bean
Anton ShumikhinbyAnton Shumikhin·Sep 4, 2024
TLDR
@Bean public List<String> myList() { return Arrays.asList("apple", "banana", "cherry"); }

Short, sweet and efficient. This method is tagged @Bean in your Spring configuration and uses Arrays.asList() to create the list.

JavaConfig, Autowiring and Ordering

Control your bean chaos

Suppose your spring project is less of an afternoon walk in the park and more like juggling with flaming swords. ServiceA, ServiceB all over the place and order seems like a foreign concept. All you need are two things:

  • Autowired: Takes care of the mess and wires up everything just the way you like it
  • Order: Manages how beans lineup
@Configuration public class AppConfig { @Autowired private ServiceA serviceA; // Welcome to the stage, ServiceA @Autowired private ServiceB serviceB; // Can't forget about ServiceB @Bean @Order(1) public String serviceAName() { return serviceA.getName(); // Who's on first, ServiceA? } @Bean @Order(2) public String serviceBName() { return serviceB.getName(); // And on second, ServiceB! } @Bean public List<String> serviceNames() { return Arrays.asList(serviceAName(), serviceBName()); // Taking a bow, together. } }

Spring-injectable and dynamically packed lists

Just as coffee beans can vary across different blends, so can our beans in our list. This is where Spring Expression Language (EL) earns its keep. It's perfect for dynamic list creation.

@Bean public List<String> dynamicList() { return new ArrayList<>(Arrays.asList( "#{serviceA.getName()}", "#{serviceB.getDescription()}" )); }

Like ordering coffee - dynamically get just what you want, when you want it.

Immutable Lists: Bean safety first

We can't have those meddling kids changing our precious beans once created, can we? Achieve this by using Collections.unmodifiableList(). Alternatively, Google Guava's Lists.newArrayList() could be your cup of tea, offering a fresh new list each time you want the bean:

@Bean public List<String> immutableGenreList() { return Collections.unmodifiableList(Arrays.asList("Sci-fi", "Fantasy", "Mystery")); }

Just like grandma's secret recipe, some things are better left unchanged.

XML Way: util:list

An XML alternative

If XML is where you feel at home, Spring's got your back. Use <util:list> when defining a list bean via XML.

<!-- Let's shake things up with XML --> <util:list id="myList" value-type="java.lang.String"> <value>apple</value> <value>banana</value> <value>cherry</value> </util:list>

The value-type attribute ensures Spring keeps naughty, mismatched elements out of our list!

Referencing: Beans within beans

Just when it couldn't get more inception-y—the ref attribute. It references other beans in your list. Mind.. blown!

<!-- Bean-ception right here --> <util:list id="myServiceList" list-class="java.util.ArrayList"> <ref bean="serviceA"/> <ref bean="serviceB"/> </util:list>

Proper properties & Annotation

Necessary annotations

Sometimes, you want a property to be compulsory. @Required offers this functionality. Try to not miss the setter method though!

public class SomeClass { private List<String> genres; @Required // Don't forget me! public void setGenres(List<String> genres) { this.genres = genres; } }

Externally Configured Lists

Spring doesn't limit you by bean definitions alone. @Value enables you to inject property values from external sources into your beans:

@Bean public List<String> externalConfiguredList(@Value("${genres.list}") String[] genres) { return Arrays.asList(genres); }

External configuration? Fancy! Instant fancy words: "Yes, my beans have external configuration."

Pitfalls and their counters

Controlled chaos with lists

In programming, anything can and will happen. Like having to maintain the order of beans within your list. With @Order, you can do just that. Programming has never been more orderly!

@Order(1) // First in, first out. @Bean public Book thrillerBook() { return new Book("Thriller"); }

No more clones

With List beans, there could be a duplicate problem. Looks like it’s time to play detective! You can fix this by ensuring unique instances in the Set or double checking your bean creation methods.

// The game is afoot! @Autowired private Set<Book> books;