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

SpringBoot开发Greeting REST接口报错:需配置long类型Bean关联AtomicLong怎么解决

错误产生原因

核心问题是你错误将@SpringBootApplication注解标注在了作为数据实体的Greeting类上:

  • @SpringBootApplication是Spring Boot用来标识应用启动入口类的专用注解,被该注解标注的类会被Spring自动识别为需要实例化并注册到容器的Bean。
  • Spring尝试实例化Greeting类时,发现它仅存在一个接收long id和String content两个参数的构造方法,而Spring容器中不存在对应基础类型的Bean,因此抛出consider defining a bean of type 'long' in your configuration的错误。
修复方案
  • 第一步:清理Greeting类的无关注解和依赖,修改后代码如下:
package com.firstgood.restservice;

public class Greeting {
    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}
  • 第二步:单独创建Spring Boot启动类,在同包路径下新增RestServiceApplication.java,代码如下:
package com.firstgood.restservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(RestServiceApplication.class, args);
    }
}
  • 第三步:Controller层的AtomicLong相关逻辑无需调整,正常在接口方法中手动构造Greeting对象即可,参考示例:
@RestController
public class GreetingController {
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:27:03