Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autowired Replacement #69

Open
Deffo0 opened this issue Dec 30, 2022 · 0 comments
Open

Autowired Replacement #69

Deffo0 opened this issue Dec 30, 2022 · 0 comments
Labels
refactoring Improve the design, structure, implementation and increase code readability and reduced complexity

Comments

@Deffo0
Copy link
Member

Deffo0 commented Dec 30, 2022

Autowired isn't necessary, as you can replace it by constructor injection which has alot of advantages as following:

  • the dependencies are clearly identified. There is no way to forget one when testing, or instantiating the object in any other circumstance (like creating the bean instance explicitly in a config class).

  • the dependencies can be final, which helps with robustness and thread-safety.

  • you don't need reflection to set the dependencies. InjectMocks is still usable, but not necessary. you can just create mocks by yourself and inject them by simply calling the constructor.

  • by the autowired approach, you are allowing anyone (in different class outside/inside the Spring container) to create an instance using default constructor (like new SomeService()), which is NOT good as you need SomeOtherService object (as a dependency) for your SomeService.

You may have some questions like "is this is applicable in the stereo type component as you don't call it?"

The answer is yes and you can do it even for JPA repositories.

how does spring inject the dependency in this case ?

Spring scans your classes for constructor that matches your class' fields. Find details here:
Additional Details

Originally posted by @Deffo0 in #65 (comment)

@Deffo0 Deffo0 added the refactoring Improve the design, structure, implementation and increase code readability and reduced complexity label Dec 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Improve the design, structure, implementation and increase code readability and reduced complexity
Projects
None yet
Development

No branches or pull requests

1 participant