user2351281
user2351281

Reputation: 137

Spring @Autowired confusing

I think I found a confusing problem. I have two classes under the package 'cao' One is:

@Repository
public class MovieFinder {
}

The other is:

public class SimpleMovieLister {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private MovieFinder movieFinder;

    public MovieFinder getMovieFinder() {
        return movieFinder;
    }

    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
}

In the application xml file,I define as follows

<bean class="cao.SimpleMovieLister"/>
<context:component-scan base-package="cao"/>
<bean id="1" class="cao.MovieFinder"/>

Then the program can run normally. But what confused me is that now we have two instances of type MovieFinder.Why not throw a exception?

After I change the @Repository to @Repository(value="2"),the expected exception is thrown. WOW,please help me. thanks a lot.

Upvotes: 0

Views: 932

Answers (2)

MariuszS
MariuszS

Reputation: 31567

But what confused me is that now we have two instances of type MovieFinder.

If you are using annotation based configuration (@Repository) then why you are configuring this bean second time <bean id="1" class="cao.MovieFinder"/> in XML? This is why you have two identical beans.

Upvotes: 0

gerrytan
gerrytan

Reputation: 41123

As mentioned on spring documentation:

By default, the autowiring fails whenever zero candidate beans are available

It doesn't really care if there's more than 1 candidates, because in fact you can autowire multiple candidates into an array / collection.

It seems whenever you have multiple candidates, it will autowire the last created beans -- but I cannot find anything on the documentation that supports this. Never rely on this behavior.

So far I haven't yet found a way to configure autowiring to fail if there's more than 1 candidate -- I guess you have to create your own BeanPostProcessor and/or override AutowiredAnnotationBeanPostProcessor

I'd say best practice is to avoid having multiple candidates, either by providing extra qualifier, or avoid creating unecessary candidates.

Upvotes: 2

Related Questions