Skip to content

Autowired Replacement #69

@Deffo0

Description

@Deffo0

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactoringImprove the design, structure, implementation and increase code readability and reduced complexity

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions