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

如何在Spring Boot中创建返回字符串数组的API?

在Spring Boot中实现返回指定字符串数组的API

1. 实现返回目标数组的方法

编写一个方法返回你需要的["Non Dox", "Dox"]数组,建议放在业务服务类中(遵循Spring依赖注入规范,避免静态方法):

import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
    // 返回指定的字符串数组,修正顺序和空格格式
    public String[] demo() {
        return new String[] {"Non Dox", "Dox"};
    }
}

2. 在控制器中调用该方法并暴露API

创建REST控制器,注入业务服务类,编写GET接口返回数组:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    private final EmployeeService employeeService;

    // 构造器注入服务类
    public DemoController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/url")
    public String[] getArray() {
        return employeeService.demo();
    }
}

补充说明

  • 启动Spring Boot应用后,访问http://localhost:8080/url即可得到["Non Dox","Dox"]的JSON响应
  • 若坚持使用静态方法,可将demo()改为静态方法,控制器中直接调用EmployeeService.demo(),但该方式不利于后续功能扩展和单元测试,不推荐使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:41:13