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

Calling a DAO method from a controller class


In this recipe, we'll see how to call a DAO method from a controller class.

Getting ready

We will use the DAO class defined in the previous recipe and pretend that it has an add(User) method. In the following recipes, we will write actual DAO methods.

How to do it…

Here are the steps to use a DAO method from a controller class:

  1. In your controller class, add the DAO as an @Autowired field:

    @Controller
    public class UserController {
      @Autowired
      private UserDAO userDAO;
    
  2. Use the DAO in any controller method:

    userDAO.add(user);

How it works…

Because of @Autowired, the userDAO field will be automatically initialized by Spring using dependency injection.