Mastering Spring @Autowired: 9 Powerful Injection Techniques

This guide explains how Spring's @Autowired annotation works across constructors, methods, fields, arrays, collections, maps, optional dependencies, and built‑in Spring components, providing code examples and tips for handling required and optional beans in a Spring 5.2.15 environment.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Spring @Autowired: 9 Powerful Injection Techniques

Environment: spring5.2.15

The @Autowired annotation first attempts injection by type; if multiple candidates exist it falls back to by name, and if no matching name is found the container throws an error. You can narrow the target with @Qualifier.

As of Spring Framework 4.3, an @Autowired annotation on a constructor is no longer necessary if the target bean defines only one constructor. However, if several constructors are available and there is no primary/default constructor, at least one constructor must be annotated with @Autowired to indicate which one the container should use.

Function 1

Inject a dependency via a setter method.

public class SimpleMovieLister {
  private MovieFinder movieFinder;
  @Autowired
  public void setMovieFinder(MovieFinder movieFinder) {
    this.movieFinder = movieFinder;
  }
}

Function 2

@Autowired can be applied to a method with any name and multiple parameters.

public class MovieRecommender {
  private MovieCatalog movieCatalog;
  private CustomerPreferenceDao customerPreferenceDao;
  @Autowired
  public void prepare(MovieCatalog movieCatalog, CustomerPreferenceDao customerPreferenceDao) {
    this.movieCatalog = movieCatalog;
    this.customerPreferenceDao = customerPreferenceDao;
  }
}

Function 3

@Autowired can be used on fields and can be mixed with constructor injection.

public class MovieRecommender {
  private final CustomerPreferenceDao customerPreferenceDao;
  @Autowired
  private MovieCatalog movieCatalog;
  @Autowired
  public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
    this.customerPreferenceDao = customerPreferenceDao;
  }
}

Function 4

Inject an array of beans by annotating a field or method.

public class MovieRecommender {
  @Autowired
  private MovieCatalog[] movieCatalogs;
}

Function 5

Inject a collection (Set) of beans via a field or method.

public class MovieRecommender {
  private Set<MovieCatalog> movieCatalogs;
  @Autowired
  public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
    this.movieCatalogs = movieCatalogs;
  }
}

Note: To preserve order when injecting a List or array, implement the Ordered interface, use @Order, or the standard @Priority annotation. A Set does not guarantee order.

Function 6

Inject a Map of beans, where the key is the bean name.

public class MovieRecommender {
  private Map<String, MovieCatalog> movieCatalogs;
  @Autowired
  public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
    this.movieCatalogs = movieCatalogs;
  }
}

Note: For arrays, collections, or maps, at least one matching bean must exist; otherwise an error occurs.

By default, @Autowired marks a dependency as required, causing an error if the bean is missing. You can change this behavior:

public class SimpleMovieLister {
  private MovieFinder movieFinder;
  @Autowired(required = false)
  public void setMovieFinder(MovieFinder movieFinder) {
    this.movieFinder = movieFinder;
  }
}

Note: If no suitable MovieFinder bean exists, the setter will not be called. Constructor injection will still fail even with required = false.

Function 7

Use Java 8's java.util.Optional to represent an optional dependency.

public class SimpleMovieLister {
  @Autowired
  public void setMovieFinder(Optional<MovieFinder> movieFinder) {
    // optional handling
  }
}

Function 8

Mark a dependency as optional with the @Nullable annotation.

@Autowired
public void setMovieFinder(@Nullable MovieFinder movieFinder) {
  System.out.println("-----movie");
  this.movieFinder = movieFinder;
}

Function 9

@Autowired can inject built‑in Spring components such as BeanFactory, ApplicationContext, Environment, ResourceLoader, ApplicationEventPublisher, and MessageSource.

@Autowired
private ApplicationContext context;
The @Autowired, @Inject, @Value, and @Resource annotations are processed by Spring BeanPostProcessor implementations. They cannot be used inside custom BeanPostProcessor or BeanFactoryPostProcessor classes; those must obtain beans via XML configuration or @Bean methods.

End of guide.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend Developmentspringdependency-injectionAutowired
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.