Spring Boot Guides Examples(1~3)

参考网址:https://spring.io/guides

创建一个RESTful Web Service

  • 使用Eclipse 创建一个 Spring Boot项目
Project -> Other -> Spring Boot -> Spring Starter Project
  • 直接找到,spring boot自动创建的application类,
#我的是 RestfulWebService1Application.java
右键 -> Run As -> Java Application 运行
------------------console result---------------------
#看见下面两行,则开启成功
2019-02-24 10:38:42.935  INFO 6724 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-02-24 10:38:42.940  INFO 6724 --- [           main] c.e.kane.RestfulWebService1Application   : Started RestfulWebService1Application in 4.108 seconds (JVM running for 5.631)
  • 打开浏览器,键入 localhost:8080会得到下面的报错信息,因为我们还没有定义Controller
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.Sun Feb 24 10:39:50 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
## 可以参考下面的网址,对Whitelabel Error Page 自定义
https://www.baeldung.com/spring-boot-custom-error-page

注:可以自定义该页面,到官网查看

  • 开始写如一些java类
// 在Application同级目录下创建Model 文件夹,增加Greeting 类
// Greeting.java
package com.example.kane.Model;
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;}
}
// 在Application同级目录下创建 Controller文件夹,增加GreetingController
// GreetingController.java
package com.example.kane.Controller;import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;// RestController是Spring4的新的注解,被注解的controller返回域对象,不是view// 它是@Controller和@ResponseBody的缩写
import org.springframework.web.bind.annotation.RestController;
import com.example.kane.Model.*;
@RestController
public class GreetingController {private static final String template = "Hello, %s!";private final AtomicLong counter = new AtomicLong();@RequestMapping("/greeting")public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {return new Greeting(counter.incrementAndGet(),String.format(template, name));}
}
  • 访问 localhost:8080/greeting
# 页面结果
{"id":1,"content":"Hello, World!"}
  • 至此一个简单的Restful Web Service 搭好了

注:官方的关于Restful Web Service 网址 https://spring.io/guides/gs/rest-service/

创建一个计划的任务 Scheduling Tasks

  • 创建schdule task类
package com.example.kane;
import java.text.SimpleDateFormat;
import java.util.Date;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Componentpublic class SchduleTask {private static final Logger log = LoggerFactory.getLogger(SchduleTask.class);private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");@Scheduled(fixedRate = 5000)public void reportCurrentTime() {log.info("The time is now {}", dateFormat.format(new Date()));}
}
  • 更改Application 类,增加@EnableScheduling
package com.example.kane;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class RestfulWebService1Application {public static void main(String[] args) {SpringApplication.run(RestfulWebService1Application.class, args);}}
  • 结果,会在console中看到如下输出
2019-02-24 12:00:14.770  INFO 21096 --- [   scheduling-1] com.example.kane.SchduleTask             : The time is now 12:00:14
2019-02-24 12:00:19.770  INFO 21096 --- [   scheduling-1] com.example.kane.SchduleTask             : The time is now 12:00:19
2019-02-24 12:00:24.770  INFO 21096 --- [   scheduling-1] com.example.kane.SchduleTask             : The time is now 12:00:24## 不停地运行Schdule函数
  • 其他的Schdule选项

https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling

// 等待上一个执行之后5秒执行下一次
@Scheduled(fixedDelay=5000)
//-------------------------------------
//上一次开启之后5秒执行下一次,无论第一次是否执行完成
@Scheduled(fixedRate = 5000)
//-------------------------------------
// 使用cron 进行定时的安排,语法与linux cronjob相同
@Scheduled(cron="*/5 * * * * MON-FRI")

注:cron表达式规则

Seconds Minutes Hours DayofMonth Month DayofWeek Year
或
Seconds Minutes Hours DayofMonth Month DayofWeek
字段 允许值 允许的特殊字符
秒(Seconds) 0~59的整数 , - * / 四个字符
分(Minutes 0~59的整数 , - * / 四个字符
小时(Hours 0~23的整数 , - * / 四个字符
日期(DayofMonth 1~31的整数(但是你需要考虑你月的天数) ,- * ? / L W C 八个字符
月份(Month 1~12的整数或者 JAN-DEC , - * / 四个字符
星期(DayofWeek 1~7的整数或者 SUN-SAT (1=SUN) , - * ? / L C # 八个字符
年(可选,留空)(Year 1970~2099 , - * / 四个字符

## 消费一个Restful Web Service

这里的消费意为在java中访问一些Restful API 并获得想要的内容。

  • 更改 Application.java文件
package com.example.kane;import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
public class RestfulWebService1Application {private static final Logger log = LoggerFactory.getLogger(RestfulWebService1Application.class);public static void main(String[] args) {
//      不启动Spring boot的application,直接运行RestTemplate
//      SpringApplication.run(RestfulWebService1Application.class, args);RestTemplate restTemplate = new RestTemplate();System.out.println(Quote.class);Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);log.info(quote.toString());}/*  下面的代码官方说明是要管理RestTemplate,不明白什么意思@Beanpublic RestTemplate restTemplate(RestTemplateBuilder builder) {return builder.build();}@Beanpublic CommandLineRunner run(RestTemplate restTemplate) throws Exception {return args -> {Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);log.info(quote.toString());};}*/
}
  • 定义一个Quote.java类
// Quote 定义的时候需要知道 restful api 返回的json对象都有什么属性,如果Quote中定义的属性在api中不存在那么将被复制为null,
//我将官网的type属性更改为 type1属性后,结构显示type1:null
package com.example.kane;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {private String type1;private Value value;public Quote() {}public String getType() {return type1;}public void setType(String type) {this.type1 = type;}public Value getValue() {return value;}public void setValue(Value value) {this.value = value;}@Overridepublic String toString() {return "Quote{" +"type='" + type1 + '\'' +", value=" + value +'}';}
}
  • 定义Value.java
//value 与 quote相同,定义了这两个类 主要是http://gturnquist-quoters.cfapps.io/api/random返回的json对象中有这两个类
package com.example.kane;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {private Long id;private String quote;public Value() {}public Long getId() {return this.id;}public String getQuote() {return this.quote;}public void setId(Long id) {this.id = id;}public void setQuote(String quote) {this.quote = quote;}@Override    public String toString() {return "Value{" +"id=" + id +", quote='" + quote + '\'' +'}';}
}
  • 上结果
20:59:39.613 [main] INFO com.example.kane.RestfulWebService1Application - Quote{type='null', value=Value{id=4, quote='Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration.'}}

转载于:https://www.cnblogs.com/primadonna/p/10433438.html

【Spring Boot】构造、访问Restful Webservice与定时任务相关推荐

  1. Spring boot集成axis2开发webservice 服务

    Spring boot集成axis2开发webservice 服务 1.新建Spring boot 项目 此处省略... 项目结构如下: 2.添加Axis2依赖 <!--axis2版本信息--& ...

  2. java restful接口开发实例_实战:基于Spring Boot快速开发RESTful风格API接口

    写在前面的话 这篇文章计划是在过年期间完成的,示例代码都写好了,结果亲戚来我家做客,文章没来得及写.已经很久没有更新文章了,小伙伴们,有没有想我啊.言归正传,下面开始,今天的话题. 目标 写一套符合规 ...

  3. 使用Spring Rest和Spring Data JPA和H2以及Spring Boot示例的Restful API

    你好朋友, 在本教程中,您将学习以下内容: 1.在Spring Boot中配置Spring Rest,Spring Data JPA和H2 2.使用Spring Boot创建Springful服务端点 ...

  4. Spring Boot设置访问url接口后缀

    传统的xml配置方式 <!--Spring MVC 配置--> <servlet><servlet-name>dispatcherServlet</servl ...

  5. 无返回值_只需一步,在Spring Boot中统一Restful API返回值格式与处理异常

    统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: public cl ...

  6. mysql的每隔1分钟定时_简单易用,spring boot集成quartz,实现分布式定时任务

    什么是quartz? Quartz是一个完全由 Java 编写的开源任务调度框架. 我们经常会遇到一些问题: 想每个月27号,提醒信用卡还款: 想每隔1小时,提醒一下,累了,站起来活动一下: 想每个月 ...

  7. [快速入门]Spring Boot+springfox-swagger2 之RESTful API自动生成和测试

    Swagger是自动生成 REST APIs文档的工具之一.Swagger支持jax-rs, restlet, jersey.springfox-swagger是Spring生态的Swagger解决方 ...

  8. Spring Cloud + Spring Boot + Mybatis + shiro + RestFul + 微服务

    摘要: Commonservice-system是一个大型分布式.微服务.面向企业的JavaEE体系快速研发平台,基于模块化.服务化.原子化.热插拔的设计思想,使用成熟领先的无商业限制的主流开源技术构 ...

  9. Spring Boot注解完成Restful API

    利用注解完成Restful API @RestController public class HelloController { @RequestMapping("/hello") ...

最新文章

  1. 大胆,用Python爬一爬都是哪些程序员在反对996?!
  2. COJ 1008 WZJ的数据结构(八) 树上操作
  3. 2021-03-02 英文写作中的“但是”
  4. java运行jar命令提示没有主清单属性
  5. 记一次曲折的jsp手工半盲注入
  6. robotframework安装_python3.9.0 + robotframework + selenium3 实例体验
  7. cdr 表格自动填充文字_PS那些好用到哭的新手小技巧(1)——如何快速去除文字图片的水印或背景文字?...
  8. 【sql绕过】Bypass waf notepad of def
  9. Ubuntu12.04编译Android4.0.1源码全过程-----附wubi安装ubuntu编译android源码硬盘空间不够的问题解决
  10. LeetCode-107二叉树的层次遍历 II-BFS实现
  11. 执行计划有时不准确_一张表格,帮助学生制定良好每日学习计划,提升学习积极性主动性...
  12. 多维数组的本质和指针数组
  13. Android M 设置里面关于手机型号的修改
  14. 内插函数恢复模拟信号
  15. 基于php的物流系统设计与实现
  16. Ubuntu16安装VScode、linux安装vscode、极简极稳安装vscode、umake安装vscode
  17. 远程控制工具——Centos7上向日葵安装使用(xy)
  18. 宝塔面板搭建WordPress网站完整教程
  19. LINUX——正则表达式
  20. excel保存快捷键_这些快捷键,你都知道吗?

热门文章

  1. 数据可视化的实现技术和工具比较(HTML5 canvas(Echart)、SVG、webGL等等)
  2. 微信每日早安推送 Windows版
  3. Android 新浪微博 授权失败 21337
  4. nm命令和其内容详解
  5. 个人博客网站建设详细版
  6. Java小技巧输出26个英文字母,不用一个一个手打
  7. 迅雷链:DPoA 与 VRF
  8. jadx反编译—下载和使用
  9. 计算语言学之语言理解与认知(1)
  10. Java处理CSV或者制表符等分隔文件,比如Maf文件