我的Spring-MVC项目中有UserBean来存储用户。
@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserBeanImpl implements UserBean {
private User user;
@Override
public User getUser() {
return user;
}
@Override
public UserBean setUser(User user) {
this.user = user;
return this;
}
}
我可以将其自动装入服务层吗?我应该只将它自动装入控制器吗?
第一种方式(autowire进入服务):
@Service
public class MyServiceImpl implements MyService {
@Autowired
UserBean userBean;
@Override
public void doSomething(int id) {
dao.doSomething(id,userBean.getUser());
}
第二种方式(自动装入cotroller):
@Service
public class MyServiceImpl implements MyService {
@Override
public void doSomething(int id, User user) {
dao.doSomething(id, user);
}
}
@Controller
public class MyController {
@Autowired
UserBean userBean;
@RequestMapping(value = {"/"})
public void do(@RequestParam("id") int id) {
myService.doSomething(id, userBean.getUser());
}
}
Spring MVC-Service-DAO架构有什么好处?
答案 0 :(得分:0)
@Service
public class MyServiceImpl implements MyService {
@Autowired
UserBean userBean;
@Override
public void doSomething(int id) {
dao.doSomething(id,userBean.getUser());
}
这是最好的方式(服务),因为控制器层应该用于获取请求,发送响应并调用服务来运行业务逻辑。保存用户是服务层任务。