tags:

views:

30

answers:

2

When you mark something with the Autowire annotation, you are saying you want this particular e.g. class to be automatically wired for DI.

Now where exactly do you set the target class to be used in the Autowire?

reference: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config

so in this example below, you autowire the setter:

public class SimpleMovieLister {

    private MovieFinder movieFinder;

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

    // ...
}

Will spring just search for any class that implements the interface MovieFinder?

+2  A: 

If there is a bean of type MovieFinder in the context, it will be injected. If there are more than one beans of that type, an exception will be thrown.

In the case of constructor injection, @Autowired (and @Required I assume) are only autowire-by-type.

If you want to explicitly specify a name using annotations, use @Resource(name="beanId")

Bozho
its nice having everything in one place sometimes i.e xml file
Blankman
well, no, annotations make perfect sense if you master them.
Bozho
I see, well if you have 1+ implementations you said you can specificy the beanId, but then you need to declare the beans in XML or can you set the beanID via annotations?
Blankman
you can set the ids via annotations. Also, they have default ids. for example `@Component public class SomeBeanImpl` has the default name `someBeanImpl`
Bozho
+2  A: 

Will spring just search for any class that implements the interface MovieFinder?

Essentially, yes. It gets interesting when it finds more than one, upon which it will throw an exception on context startup, unless you take steps to help it out.

There are 3 ways to address multiple autowire candidates:

  • Mark the ones you don't want to autowire with autowire-candidate="false".
  • Mark the one you do want to autowire with primary="true"
  • Qualify the @Autowired annotation by specifying @Qualifier("TheBeanIWant")

Any of the above will work, you pick the one that suits your situation best.

@Qualifier("TheBeanIWant") and @Resource(name="TheBeanIWant") are rather similar, the difference is that @Qualifier is helping Spring narrow down the autowiring, whereas @Resource is explicitly picking out a bean by name, regardless of type.

skaffman