Search code examples
springspring-beanspring-context

Spring Context doesn't seem to recognize a Bean when creating it with stereotype annotations. Throws NoSuchBeanDefinitionException


I'm following a book to learn some modules of the Spring ecosystem. Currently trying to create beans using stereotype annotations. I've written a simple Java class and marked it as a component:

package main.parrot;
@Component
public class Parrot {
  private String name;
  // getters and setters //
}

I then created a @Configuration class which scans for the Parrot component:

package main;
//imports
@Configuration
@ComponentScan(basePackages = "parrot")
public class ProjectConfig{}

In my main method I am creating a spring context using the configuration above, and I'm trying to access the bean Parrot:

package main;
//imports//
public class Main{
  public static void main(String...args){
    var context = new AnnotationConfigApplicationContext(ProjectConfig.class);
    var p = context.getBean(Parrot.class);
  }
}

The line of code in which I attempt to get the Parrot bean throws the following exception: NoSuchBeanDefinitionException: No qualifying bean of type 'main.parrot.Parrot' available

I just don't understand why this configuration wouldn't find the Parrot bean. If someone could help me clarify the issue I would be extremely grateful.

Thank you in advance


Solution

  • You need to change the basePackages to include the complete package name:

    package main;
    //imports
    @Configuration
    @ComponentScan(basePackages = "main.parrot")
    public class ProjectConfig{}