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:
- In the controller class, add a
UserService
field annotated with@Autowired
:@Autowired UserService userService;
- In a controller method, use the
UserService
field:@RequestMapping("hi") @ResponseBody public String hi() { return "nb of users: " + userService.findNumberOfUsers(); }
- In a web browser, go to
http://localhost:8080...