You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 中如何将 model 变量传递到 service 层?

Spring Boot 中传递Model变量到Service层的实现方案

首先需要明确:Spring 中的 Model 是 Web 层专属的组件,设计目的是承载 Controller 到视图层的渲染数据,原则上不推荐直接传递到 Service 层,会破坏分层架构的解耦原则。如果确实有相关需求,可以参考以下两种实现方案:

方案1:直接作为方法参数传递(仅适合临时小项目使用)

直接把Model作为Service方法的入参传递,实现最简单:

  • Service层方法声明时,直接引入org.springframework.ui.Model作为入参
  • Controller层调用Service方法时,把当前请求绑定的Model对象直接传入即可

代码示例

Service层代码

import org.springframework.ui.Model;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void getUserInfo(Long userId, Model model) {
        // 执行业务逻辑查询用户信息
        User user = userMapper.selectById(userId);
        // 直接把业务结果写入Model
        model.addAttribute("userInfo", user);
    }
}

Controller层代码

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/user/detail")
    public String userDetailPage(Long userId, Model model) {
        // 调用Service时直接传入Model对象
        userService.getUserInfo(userId, model);
        return "userDetail";
    }
}

弊端:Service层和Web层强耦合,Service无法在定时任务、RPC调用等非Web场景下复用,不符合架构设计规范。

方案2:分层解耦实现(生产环境推荐)

Service层只负责返回业务结果,由Controller层负责把结果写入Model,完全解耦两层依赖:

  • Service层方法只处理业务逻辑,返回需要写入Model的键值对集合
  • Controller层接收Service返回的结果,统一写入Model对象

代码示例

Service层代码

import java.util.Map;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    public Map<String, Object> getUserInfo(Long userId) {
        // 执行业务逻辑查询用户信息
        User user = userMapper.selectById(userId);
        // 封装业务结果返回,完全不依赖Web层类
        return Map.of("userInfo", user);
    }
}

Controller层代码

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/user/detail")
    public String userDetailPage(Long userId, Model model) {
        // 调用Service获取业务结果
        Map<String, Object> serviceResult = userService.getUserInfo(userId);
        // Controller层负责把结果写入Model
        model.addAllAttributes(serviceResult);
        return "userDetail";
    }
}

优势:Service层完全不依赖Web层组件,可在任意场景下复用,符合分层架构的单一职责原则。

内容的提问来源于stack exchange,提问作者Oya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:15:04