Spring:使模型可供控制器使用的正确方法?
给定以下控制器,配置
@Controller
public class MyController
{
...
@RequestMapping("/data")
public @RequestBody Data getData(@RequestParam String id)
{
return myCustomModel.queryForData(id);
}
}
它以便 MyController 可以使用 myCustomModel
(查询 Data
的内容)的正确方法是什么?我已经看到了自动装配的这种奇妙之处,我也想这样做。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于生产代码,明智的做法是显式声明依赖项而不是使用自动装配,这样生产设置中的移动部件就会减少。
这类似于仅使用完全限定的导入语句而不是 import my.super.project.dao.* 的良好实践
(顺便说一下,自动装配对于集成测试来说是一个非常有用的功能)
所以要挂钩在生产中,一个好的方法是将普通的旧构造函数依赖注入到最终字段中。尽可能使用最终字段最大限度地减少可变性。
服务类,通过注入接收daos:
然后控制器通过注入接收服务(使用接口类型):
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:
And then the controller receives the service through injection (using the interface type):
你的控制器不应该直接调用 DAO 层(原因很简单,如果你想做一些事务,你的控制器层不支持它)。您必须注入一个服务 (@Service) 并从中调用一个服务方法,该方法可以在事务范围内内部调用一个或多个 DAO 方法,并返回最终的模式供您发送到视图。
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.