Today a question went out on a Spring mailing list asking about @Autowired dependencies, AOP proxies, and interfaces. I thought this was a great foundation question. So I thought I’d share it here.
Say you have a bean class, Foo which implements FooInterface. On top of that, the bean is advised via Spring AOP it is the proxy class which is referenced by the context (IOC). Now, let’s say you want to autowire that dependency in another bean. So you mark the Foo field @Autowired. You fire up you application. Much to your dismay, you’ll get an error message on context initialization which goes something like, “unsatisfied dependency.” This is due to the fact that you are trying to autowire an object by its class but that class has been proxied. Meaning that there are no beans of this type in context.
So, you remember that its a great idea to code against interfaces rather than concrete classes. So you adjust your field type to FooInterface and fire up the application again. Unfortunately, you forgot that there are several instances of FooInterface in context and you get another error on startup. “No unique bean of type…”
So how would I autowire a specific bean out of a set? The answer is the handy @Qualifier annotation. Adding this to your autowired field let’s you specify the bean id/name to inject. In this case you’d use something like @Qualifier(“stevesFoo”). Boom. Done.