Using a bean directly

It's possible to get a bean directly from Spring instead of using dependency injection by making Spring's ApplicationContext, which contains all the beans, a dependency of your class. In this recipe, we'll inject an existing bean into 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 get and use a bean directly:

  1. In the controller class, add an ApplicationContext field annotated with @Autowired:
    @Autowired
    private ApplicationContext applicationContext;
  2. In a controller method, use the ApplicationContext object and its getBean() method to retrieve the UserService bean:
    UserService userService = (UserService)applicationContext. ...

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.