Preferring constructor injection over setter injection for mandatory dependencies

There are two kinds of dependencies for beans:

  • Mandatory dependencies: These are dependencies that you want to be available for the bean. If the dependency is not available, you would want the context to fail loading up.
  • Optional dependencies: These are dependencies that are optional. They are not always available. It's fine to load the context even if these are not available.

We recommend that you wire mandatory dependencies using constructor injection instead of setter injection. This would ensure that the context would fail to load if the mandatory dependency is missing. The following snippet shows an example:

    public class SomeClass { private MandatoryDependency ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.