SpringBoot-完成簡單服務接口實現

上篇介紹了新手搭建SpringBoot工程,這篇文章主要介紹如何在SpringBoot工程中開發,所需要的接口。簡單易懂,一起學習下。

在SpringBoot中沒有SpringMvc繁瑣的配置,下面只是簡單介紹一個hello的rest服務接口的開發。

首先,你需要明白,在SpringBoot中,包的掃描是基於啓動工程所在包以及該包下的子包。如下:

如上,我的啓動工程包名爲com.example.springboot,即該包以及該包下的子包都可以被SpringBoot工程識別。

下面簡單開發一個helloword的服務接口,如下:

package com.example.springboot.control;

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

@RestController
@RequestMapping("")
public class HelloController {

	@RequestMapping("/hello")
	public String sayHello(){
		return "welcome to springboot world.";
	}
}

可以看到,這裏沒有我們之前熟悉的註解@Controller,簡答來說,@RestController註解它是由@Controller註解和@ResponseBody組合合成,但是@RestController註解如何返回到頁面上面去,返回的數據無法進行解析jsp,html.返回的內容就是接口返回的數據。

使用@Controller註解,可以返回到jsp,html界面。如果想返回json等數據格式。則需要增加註解@ResponseBody註解。

啓動工程,如下:

即完成一個服務接口的開發,下一篇介紹SpringBoot如何集成JPA完成數據庫操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章