开发者

When using Autowire, where do you set the bean you want wired up?

开发者 https://www.devze.com 2022-12-19 12:20 出处:网络
When you mark something with the Autowire annotation, you are saying you wa开发者_StackOverflow社区nt this particular e.g. class to be automatically wired for DI.

When you mark something with the Autowire annotation, you are saying you wa开发者_StackOverflow社区nt 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?


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.


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")

0

精彩评论

暂无评论...
验证码 换一张
取 消