Book Image


Book Image


Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
About the Author
About the Reviewers

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:

    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.getBean("userService");        

How it works…

When the controller class is instantiated, Spring automatically initializes the @Autowired field with its ApplicationContext object. The ApplicationContext object references all...