Why instantiating objects using new keyword is hardcoded?

Asked

Viewed 56 times

2

I am learning Spring, and several times I have come across instructors solving the "problem" of instantiation of objects being made by keyword new, as in:

private SpeakerRepository repository = new HibernateSpeakerRepositoryImpl();

Normally, to solve this, they use the Autowired (dependency injection) annotation, with the justification that use instantiation by new, leaves hard coded code.

I can’t understand how the keyword new leaves hard-coded code.

Thank you so much for your help!

  • The question of being considered "Hard Coded" is that preference should be given to using the Spring dependency management mechanism. Create @Bean and inject using the @Autowired, it is preferable to use a constructor to receive the dependencies than to use the @Autowired on the estates.

1 answer

0

Imagine now that your Speakerrepository is used in 40 classes, and for some reason you need to change the implementation in all of them, it would give you a lot of work, but if the implementation is in the bean

Now imagine that

@ Bean
public SpeakerRepository speakerRepository(){
return new HibernateSpeakerRepositoryImpl()
}

If you need to change, only this line will be changed and spring will understand that it has changed everywhere.

  • 1

    That alone is no advantage. Classes that use the repository should only depend on the interface, whereas the implementation can be passed both via traditional dependency injection (constructor Injection) as via an DI framework like Spring. Once you can change the implementation of either one of the two ways in a single point. The advantage I see is the choice of implementation to be made at runtime and not compilation, I just don’t know the clear benefit of it. Nor is separating usage settings an exclusive advantage. The disadvantage: it removes instantiation from the place where it is used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.