views:

41

answers:

2

Given the following controller,

@Controller
public class MyController 
{
    ...

    @RequestMapping("/data")
    public @RequestBody Data getData(@RequestParam String id) 
    {
        return myCustomModel.queryForData(id);
    }
}

what is the proper way to configure it so that myCustomModel (something that is queried for Data) is available to MyController? I've seen this sort of fanciness with autowiring, and I'd like to do it too.

A: 

Your controller should never call the DAO layer directly (Simple reason if you want to do some transactions, your Controller layer doesn't support it). You have to inject a service (@Service) and call a service method from it which can internally call one or more DAO methods in a transactional scope and return the final modal for you to send to a view.

Teja Kantamneni
A: 

For production code, it's prudent to declare dependencies explicitly rather than using autowire, so that there are fewer moving parts in the production setup. This is similar to good practice of using only fully qualified import statements instead of import my.super.project.dao.*

(Autowiring by the way is a very useful feature for integration tests)

So to hook things up in production, a good way to go is just plain old constructor dependency injection into final fields. Using final fields where possible minimizes mutability.

Service class, which receives the daos through injection:

public class CompanyService implements ICompanyService {

   private final EmployeeDao employeeDao;
   private final DepartmentDao departmentDao;

   public CompanyService(EmployeeDao employeeDao, DepartmentDao departmentDao) {

     this.employeeDao = employeeDao;
     this.departmentDao = departmentDao;
   }

   ...
}

And then the controller receives the service through injection (using the interface type):

@Controller
public class MyController 
{
    private final ICompanyService companyService;

    public MyController(ICompanyService companyService) {
      this.companyService = companyService;
    }

    @RequestMapping("/data")
    public @RequestBody Data getData(@RequestParam String id) 
    {
        return companyService.queryForData(id);
    }
}
oksayt