Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Autowiring of Parameterized Collection

Tags:

java

spring

Hello everyone and thanks for the help in advance.

I am having a problem where Spring cannot autowire a parametirized member variable of type ArrayBlockingQueue.

Here is the java code:

@Controller
public class SomeController
{
    @Autowired
    private ArrayBlockingQueue<SomeCustomType> myQueue;
}

and in the spring configuration xml:

<bean id="myQueue" class="java.util.concurrent.ArrayBlockingQueue">
    <constructor-arg value="10"/>
</bean>

Specifying the type (SomeCustomType) for the ArrayBlockingQueue seems to confuse spring which fails to find a match and does not perform the autowiring.

Any ideas on how to get this to work? I know I can create my own wrapper class(around ArrayBlockingQueue) that is not parametirized but I would rather not if there is a better way to go about solving this.

like image 211
Quantum_Entanglement Avatar asked Oct 04 '11 23:10

Quantum_Entanglement


People also ask

Can we Autowire parameterized constructor?

3) constructor autowiring modeIn case of constructor autowiring mode, spring container injects the dependency by highest parameterized constructor. If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection will be performed by calling the two-arg constructor.

How do you Autowire for parameterized constructor in Spring boot?

You need to specify this bean in the constructor: @Component public class MainClass { private final AnotherClass anotherClass; // this annotation is NOT required if there is only 1 constructor, shown for clarity. @Autowired MainClass(AnotherClass anotherClass) { this.

Can we use @autowired without @component?

So the answer is: No, @Autowired does not necessarily mean you must also use @Component . It may be registered with applicationContext. xml or @Configuration+@Bean .

What does @autowired do in Spring?

Starting with Spring 2.5, the framework introduced annotations-driven Dependency Injection. The main annotation of this feature is @Autowired. It allows Spring to resolve and inject collaborating beans into our bean.


1 Answers

If you're trying to auto wire a collection with annotations, then use @Resource instead of @Autowired.

In order to satisfy an @Autowired collection dependency, the IoC container looks for elements of the right type to build such a collection from. In other words, it does not look for the collection itself, but rather builds a collection out of other beans.

For more information, see the Spring docs, ex. here.

like image 145
jtoberon Avatar answered Oct 23 '22 19:10

jtoberon