Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autowire factorybean

Tags:

java

spring

I have a ServiceListFactoryBean which creates a list of service implementations:

<bean id="services"
      class="org.springframework.beans...ServiceListFactoryBean"
      p:serviceType="ServiceInterface"/>

I can access the services using the applicationContext without a problem:

    final List services = ctx.getBean("services", List.class));

I can also use trad constructor-arg injection successfully:

<bean id="aClass" class="AClass">
    <constructor-arg ref="services"/>
</bean>

But if I try to autowire the dependency

@Autowired @Qualifier("services") private List services;

Then I get a BeanCreationException caused by

FatalBeanException: No element type declared for collection [java.util.List]

I am using Spring 3.0.

like image 460
Paul McKenzie Avatar asked Jan 28 '10 08:01

Paul McKenzie


People also ask

Can we use @autowired in pojo?

The beans can be wired via constructor or properties or setter method. For example, there are two POJO classes Customer and Person. The Customer class has a dependency on the Person. @Autowired annotation is optional for constructor based injection.

How do I Autowire a Spring bean?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.

How do you Autowire a false required?

By default, the @Autowired annotation implies that the dependency is required. This means an exception will be thrown when a dependency is not resolved. You can override that default behavior using the (required=false) option with @Autowired .

Is @autowired used for dependency injection?

Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.


2 Answers

It turns out that the answer is ...

@Resource(name="services") private List services;
like image 74
Paul McKenzie Avatar answered Oct 17 '22 16:10

Paul McKenzie


The exception message is from DefaultListableBeanFactory, and it's complining that it can't autowire your field because the List has no generic type (see DefaultListableBeanFactory line 716).

Try adding a generic signature to your field, e.h.

@Autowired @Qualifier("services") private List<Service> services;
like image 31
skaffman Avatar answered Oct 17 '22 15:10

skaffman