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 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;
  2. In a controller method, use the UserService field:

    @RequestMapping("hi")
    @ResponseBody
    public String hi() {
      return "nb of users: " + userService.findNumberOfUsers();
    }
  3. In a web browser, go to http://localhost:8080/hi to check whether it's working...