spring boot 输出简单 json格式的数据(利用分层结构)

来源:互联网 发布:js时间倒计时代码 编辑:程序博客网 时间:2024/06/06 00:21

    • 参考
    • 功能
    • 技术与IDE
    • 代码参考github
    • 代码片段
      • 分层结构
      • model Hellojava
      • responsitory HelloResponsitoryjava
      • service HelloServicejava
      • 启动类
      • 访问url
    • Junit测试类

参考:

spring boot 利用分层结构输出简单的Hello world

本节把spring boot 利用分层结构输出简单的Hello world
中的输出改为json格式,只需要稍作修改即可

功能

编写一个返回格式是json格式的数据。例如:

{“username”:”mike”,”age”:27}

技术与IDE

spring boot
IntelliJ IDEA

代码参考github:

Json

代码片段

分层结构

这里写图片描述

model – Hello.java

package com.yubai.springbootjson.model;public class Hello {    private String username;    private int age;    public Hello(String username, int age) {        this.username = username;        this.age = age;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

responsitory – HelloResponsitory.java

package com.yubai.springbootjson.responsitory;import com.yubai.springbootjson.model.Hello;import org.springframework.stereotype.Repository;@Repositorypublic class HelloResponsitory {    public Hello sayHello() {        Hello hello = new Hello("jolie", 27);        return hello;    }}

service – HelloService.java

package com.yubai.springbootjson.service;import com.yubai.springbootjson.model.Hello;import com.yubai.springbootjson.responsitory.HelloResponsitory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloService {    @Autowired    private HelloResponsitory helloResponsitory;    @RequestMapping("/hello")    public Hello SayHello(){        Hello hello =  helloResponsitory.sayHello();       return hello;    }}

启动类

package com.yubai.springbootjson;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootJsonApplication {    public static void main(String[] args) {        SpringApplication.run(SpringBootJsonApplication.class, args);    }}

访问url:

这里写图片描述

Junit测试类

详情请见代码参考github

原创粉丝点击