Using a bean via dependency injection with @Autowired

Spring configuration beans, such as the one in the Defining a bean explicitly with @Bean recipe are automatically discovered and used by Spring. To use a bean (any kind of bean) in one of your classes, add the bean as a field and annotate it with @Autowired. Spring will automatically initialize the field with the bean. In this recipe, we'll use an existing bean in a controller class.

Getting ready

We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService bean.

How to do it…

Here are the steps to use an existing bean in one of your classes:

  1. In the controller class, add a UserService field annotated with @Autowired:
    @Autowired UserService userService; ...

Get Spring Cookbook 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.