Sobes.tech
Junior — Middle

What is the correct way to inject dependencies using the Autowired annotation in Spring — on the field or through the constructor?

sobes.tech AI

Answer from AI

It is more correct to inject dependencies through the constructor using the @Autowired annotation in Spring. This approach has several advantages:

  • Explicit dependencies: all necessary components are visible in the constructor.
  • Ensuring immutability: dependencies can be declared as final, which increases code safety.
  • Simplified testing: it's easy to create class instances with the required mocks.
  • Avoiding issues with reflection and proxies: field injection can cause difficulties when using certain tools.

Example:

@Component
public class MyService {
    private final Dependency dep;

    @Autowired
    public MyService(Dependency dep) {
        this.dep = dep;
    }

    // methods
}

Field injection (@Autowired on a field) is considered less preferable because it hides dependencies and complicates testing.

What is the correct way to inject dependencies using… - sobes.tech