I’m a Spring newbie and recently noticed that using @Autowired in class fields is discouraged. Instead, the use of constructors is recommended for dependency injection (DI).
The problem is that I have defined a bean that requires access to many repositories. Originally, the bean had several autowired fields holding a reference to these repositories, but now I just removed the @Autowired annotation and used the constructor to initialize them. The result is a monster constructor that will probably grow in the future as long as I create more repositories/services:
@Bean
public Syncer syncer(SatBackendApplication.AppParamService appParamService,
CustomerRepository customerRepository,
AddressRepository addressRepository,
ContactPersonRepository contactPersonRepository,
CustomerContractRepository customerContractRepository,
ProductRepository productRepository,
OrderRepository orderRepository,
OrderRepository.OrderLineRepository orderLineRepository
) {
return new Syncer(
appParamService,
customerRepository,
addressRepository,
contactPersonRepository,
customerContractRepository,
productRepository,
orderRepository,
orderLineRepository);
}
Is this really the right way to inject dependencies to a bean? Is there any less cumbersome way?
Thanks!
>Solution :
Yes, having constructors with multiple parameters is a consequence of DI. It’s a good thing, because you can then create those objects outside of DI (such as in tests) without running into problems such as uninitialized fields.
However, calling those constructors manually in your production code is not good. You shouldn’t need that @Bean method at all, just annotate the Syncer class so that Spring can @Autowire it for you where you need it.
Also consider that if you need that many dependencies, maybe your class is doing too much. See if you can split up its responsibilities into different classes.