I have a Spring's @Configuration:
@Configuration
public class MyConfiguration {
public static class BeanAAA {
}
public static class BeanBBB {
BeanAAA beanA;
public BeanBBB(BeanAAA beanA) {
this.beanA = beanA;
}
}
@Autowired
@Bean
public BeanAAA createBeanAaa() {
System.out.println("In createBeanAaa");
return new BeanAAA();
}
@Autowired
@Bean
public BeanBBB createBeanBbb(BeanAAA beanA) {
System.out.println("In createBeanBbb");
return new BeanBBB(beanA);
}
}
On the application startup, I see the log from the createBeanAaa method. The log from createBeanBbb is missing due to the NoSuchBeanDefinitionException error:
In createBeanAaa
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.test.MyConfiguration#0':
Unsatisfied dependency expressed through method 'createBeanBbb' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.test.MyConfiguration.BeanAAA' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}"
How is this possible if the BeanAAA was created just before and should be available to @Autowired. Doesn't this mechanism work if it's injected in the same @Configuration?
Spring ver: 5.2.22.RELEASE
Answer
The issue is a wrong usage of the @Autowired on @Bean methods.
The solution is to remove the @Autowired annotations from your @Bean methods:
@Configuration
public class MyConfiguration {
public static class BeanAAA {
}
public static class BeanBBB {
BeanAAA beanA;
public BeanBBB(BeanAAA beanA) {
this.beanA = beanA;
}
}
@Bean
public BeanAAA createBeanAaa() {
System.out.println("In createBeanAaa");
return new BeanAAA();
}
@Bean
public BeanBBB createBeanBbb(BeanAAA beanA) {
System.out.println("In createBeanBbb");
return new BeanBBB(beanA);
}
}

