0

I am trying to use Spring's Autowire but the Bean instantiation fails if I don't explicitly define the Bean with an @Bean annotation.

Here is a sample code:

@Component
public class Bar {
}


@Component
public class Foo {
    private final Bar bar;

    @Autowired
    public Foo(Bar bar) {
        this.bar = bar;
    }
}


@Configuration
@ComponentScan(basePackages = {"com"})
public class StringTest {

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(TestConfig.class);

        Foo foo = ctx.getBean(Foo.class);

    }

}



@Configuration
public class TestConfig {

    @Bean
    public Foo foo(Bar bar) {
        return new Foo(bar);
    }

    @Bean
    public Bar bar() {
        return new Bar();
    }

}

This is a working version, but if I comment out the bean definitions in the TestConfig class spring fails to instantiate Foo, and I get this excepiton:

> Exception in thread "main"
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type 'com.test.Foo' available  at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:347)
>   at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334)
>   at
> org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1107)
>   at com.test.StringTest.main(StringTest.java:15)

The Bean I am trying to create is a concrete class, so I thought spring should automatically find it.

Should I always explicitly define the beans in a configuration class?

Nir Brachel
  • 413
  • 3
  • 12

0 Answers0