Search code examples
springjavabeansautowiredxmlbeans

NoSuchBeanDefinitionException for bean defined in JavaConfig


I was using XML configuration on my project earlier, and everything was working.

We're moving gradually to java config, so right now I'm at a stage where I'm using a mix of Java and XML configs.

Here's the problem, there is a bean defined in my XML config : beanA.

<bean id="beanA" class="BeanA" />

The class BeanA has an autowired dependency on BeanB.

class BeanA {
     @Autowired
     BeanB beanB;
}

Earlier, this beanB was also in XML config, and it ran correctly.

Now, I have made this change, and it is no longer working :

@Configuration
class MyConfig {
    @Bean
    public BeanB beanB() {
        return new BeanB();
    }
}

Apart from adding @Configuration and @Bean annotations, is there something else required to do that I am missing?

I'm getting the following error :

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'beanB': Unsatisfied dependency expressed through field 'beanA';

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxxxxx.yyy.zzzzzzzzzzzz.abc.beanA' available:

expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Please note,

  1. I have only moved beanB to be created via java config.

  2. BeanA actually has more dependencies, so I cannot move it to java config at this stage (will be doing proper migration later).


Solution

  • Spring does not load the beans from the classes annotated with @Configuration unless it has been told to look for classes with this annotation.

    To make spring look for these classes, the following must be added in your xml configuration :

    <context:component-scan base-package="com.xxxxx.yyy.zzzz">

    It will then recursively find and initialize all the beans in the package com.xxxxx.yyy.zzzz.