Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.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...