views:

1687

answers:

2

I want to use @AutoWired to inject a non-managed bean configured with @Component into a managed bean. I'm pretty sure I have the configuration right, but for some reason I keep getting the exception:

No unique bean of type [foo.Baz] is defined: Unsatisfied dependency of type [class foo.Baz]: expected at least 1 matching bean

Based on the error, I'm guessing it's not able to find the Baz class, but I'm not sure why. It's my understanding that the context:spring-configured element in the XML config was supposed to allow me to do this. I also made sure to include the appropriate jar files (spring-weaving.jar and aspectjweaver.jar).

Here's a simple example of my set up.

My XML config:

<beans ...>
    ...

    <context:annotation-config/>
    <context:spring-configured/>
    <context:component-scan base-package="foo"/>

    <bean id="bar" class="foo.Bar"/>
    ...
</beans>

I have one managed bean:

package foo;

public class Bar {

    @Autowired
    private Baz baz;

    public void setBaz(Baz baz) {
        this.baz = baz;
    }

    ...
}

And one unmanaged bean:

package foo;

@Component
public class Baz {
    ...
}

Is there something I'm missing?

EDIT: The log lists the beans its instantiating, and foo.Baz isn't one of them. I don't know why it's not picking up the @Component annotated class.

+3  A: 

Because Bar is configured with xml, it can only be configured with xml. i.e. you can't mix them. So that "@Autowired" annotation on Baz is not getting picked up (none of the annotations would be). It is only when you add the spring annotation at class level that spring will listen to any of the other annotations.

What you'll need to do is in the xml configure the bean to be autowired by type, add a setter for that type and you'll achieve the desired behaviour.

<bean id="bar" class="foo.Bar" autowire="byType"/>

One more thing, when you annotate a bean with @Component it is a spring managed bean. Just because it is not created with xml does not mean it is unmanaged. An unmanaged bean is one you don't get from spring.

Bar and Baz are both spring managed. It is the mechanism you've chosen to define them that differs.

Michael Wiles
A complete misunderstanding of terminology on my part. Great answer. Thanks!
Alex Beardsley
A: 

The previous response is not correct, in one aspect. You can autowire beans that are otherwise configured with xml.

From section 3.4.5 in http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html:

When using XML-based configuration metadata[2], you specify autowire mode for a bean definition with the autowire attribute of the element. The autowiring functionality has five modes. You specify autowiring per bean and thus can choose which ones to autowire.

You can autowire by name, type and constructor. There is a crude example of this here: http://www.java2s.com/Code/Java/Spring/AutoWiring.htm

Jon Vaughan