Andrea
Andrea

Reputation: 16570

How can I use a DAO inside a Controller in Spring MVC?

In a Spring MVC project I've a DAO class myproj.models.UserDAO:

@Repository
@Transactional
public class UserDAO {

  // UserDAO methods ...

}

and I should use it inside a controller, say myproj.controllers.UserController:

@Controller
public class UserController {

  // UserController methods ...

  @RequestMapping(value="/{user}")
  public String create(String user) {

    // Here I want to use the UserDAO
    // ...

  }

}

How can I create an instance of the UserDAO object and use it inside a controller method?

Upvotes: 2

Views: 6523

Answers (2)

Héctor
Héctor

Reputation: 26084

User Autowired annotation to inject a bean instance of your DAO:

@Controller
public class UserController {

  @Autowired
  UserDAO userDao;

  @RequestMapping(value="/{user}")
  public String create(String user) {

    userDao.method();

  }

}

Upvotes: 0

Darshan Lila
Darshan Lila

Reputation: 5868

You could try following

@Repository
@Transactional
public class UserDAO {

  // UserDAO methods ...

}

Controller:

@Controller
public class UserController {

@Autowired //this will give you the reference to UserDAO      
UserDAO userDao; 
  // UserController methods ...

  @RequestMapping(value="/{user}")
  public String create(String user) {

    // Here I want to use the UserDAO
    userDao.userDaoMethod();
    // ...

  }

}

For more information on @Autowired explore this

Upvotes: 6

Related Questions