2

I am trying to create a list of my class object using @Autowire notation but I don't know how do I tell it the size.

For Example:

@Autowire
List<MyClassObject> listMyClassObject;

I observed that listMyClassObject always contains a single object. This behaviour is same as using like below

@Autowire
MyClassObject myClassObject;

My question is how do I specify a size for this list at runtime so that listMyClassObject is auto initialised with those many objects.I am trying to do this in spring boot

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
Akhtar
  • 93
  • 1
  • 9
  • is MyClassObject a interface or super class? If yes how many implementation classes or sub classes do u have? – pvpkiran Jun 05 '18 at 12:16
  • As far as I know, this should work `@Autowired List listMyClassObject`. Do you really have multple spring components of that type? – Steffen Harbich Jun 05 '18 at 12:17

2 Answers2

0

Spring will inject all beans of type MyClassObject in your first example.

Spring will inject the only bean of type MyClassObject in your second example. This will fail if there are more than one (or no) bean of that type in your application context.

You probably have exactly one bean of type MyClassObject in your application context, which is why both examples seem to behave the same.

If you want a List with at most n elements of type MyClassObject you will have to let Spring inject all of them (like in your first example) and then truncate the list programmatically, which might look something like this

public List<MyClassObject> getMyClassObjects() {
    return listMyClassObject.stream().limit(10).collect(Collectors.toList());
}
David
  • 3,787
  • 2
  • 29
  • 43
  • How can I truncate that list when that list itself contains just 1 object? – Akhtar Jun 05 '18 at 13:16
  • I'm not sure I understand your question - the code snippet I provided will return a list with _at most_ 10 entries. If there is only 1 element in the list, the result's size will still be 1. – David Jun 06 '18 at 13:19
0

Spring doesn't need to know the size to inject your dependencies in a list.

As shown in @Thoq's answer here : Spring autowire a list

@Component
public class Car implements Vehicle {
}

@Component
public class Bus implements Vehicle {
}

@Component
public class User {
   @Autowired
   List<Vehicle> vehicles;//contains car and bus
}

Having multiple beans of the required type is properly working with a List injection.

It looks like you would only have a single bean of this type. Can you provide your beans declarations ?

Christophe Douy
  • 813
  • 1
  • 11
  • 27