0

I have to generate a set of beans in a @Configuration class with the @PostConstruct and BeanFactoryAware.

Something like this:

@Configuration
public class MyBeansConfiguration implements BeanFactoryAware {

     @Setter
     private BeanFactory beanFactory;

     @PostConstruct
     public void beanGenerator(){
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
        configurableBeanFactory.registerSingleton("a", new AClass())
    }

    @Bean
    public BClass b() {
        return new BClass();
    }
}

The service:

@Service
public class MyServiceImpl {

 private final AClass a;
 private final BClass b;

 @Autowired
 public MyServiceImpl(AClass a, BClass b){
    this.a = a;
    this.b = b;
 }

} 

When I try to start the application, the AClass bean cannot be loaded and I get this error:

Parameter 0 of constructor in com.acme......MyServiceImpl required a bean of type 'com.acme....BClass' that could not be found.

The funny thing is that when I try to inject my beans changing the order, the application star successfully without any problems.

 @Autowired
 public MyServiceImpl(BClass b, AClass a){
    this.a = a;
    this.b = b;
 }

Why is this happening?

Mr. Lennon
  • 11
  • 3
  • 3
    why are you doing this ? why not let spring create beans for you? – Amit Phaltankar Nov 15 '19 at 01:38
  • What is the purpose of registering beans manually? I don't know your needs, but marking them with `@Component` seems to make much more sense in this situation. – Matheus Nov 15 '19 at 02:48
  • I have to create dynamically from the properties, a merge from [this](https://stackoverflow.com/a/28374147) and [this](https://stackoverflow.com/a/56651866) – Mr. Lennon Nov 15 '19 at 07:44

0 Answers0