【Spring Boot && Spring Cloud系列】构建Springboot项目 实现restful风格接口
项目代码如下:
package hello; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }
package hello; public class Greeting {
private long id;
private String content;
public Greeting(long id, String content) {
super();
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
} }
package hello; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController // shorthand for @Controller and @ResponseBody rolled together
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){
System.out.println("-------------------------");
return new Greeting(counter.incrementAndGet(),String.format(template, name));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.slp</groupId>
<artifactId>restSpringDemo1</artifactId>
<version>0.1.0</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <properties>
<java.version>1.8</java.version>
</properties> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> <repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
在Application.java中run as java application 出现:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.1.RELEASE) 2016-10-13 11:19:16.510 INFO 9864 --- [ main] hello.Application : Starting Application on QH-20160418YQMB with PID 9864 (started by sanglp in D:\rest风格的apring项目\restSpringDemo1)
2016-10-13 11:19:16.525 INFO 9864 --- [ main] hello.Application : No active profile set, falling back to default profiles: default
2016-10-13 11:19:16.713 INFO 9864 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@72f926e6: startup date [Thu Oct 13 11:19:16 CST 2016]; root of context hierarchy
2016-10-13 11:19:19.691 INFO 9864 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-10-13 11:19:19.710 INFO 9864 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-10-13 11:19:19.710 INFO 9864 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.35
2016-10-13 11:19:20.148 INFO 9864 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2016-10-13 11:19:20.148 INFO 9864 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-10-13 11:19:20.148 INFO 9864 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3451 ms
2016-10-13 11:19:20.382 INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-10-13 11:19:20.398 INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-10-13 11:19:20.398 INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-10-13 11:19:20.398 INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-10-13 11:19:20.398 INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-10-13 11:19:20.866 INFO 9864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@72f926e6: startup date [Thu Oct 13 11:19:16 CST 2016]; root of context hierarchy
2016-10-13 11:19:20.986 INFO 9864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2016-10-13 11:19:20.986 INFO 9864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-10-13 11:19:20.986 INFO 9864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-10-13 11:19:21.033 INFO 9864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-13 11:19:21.033 INFO 9864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-13 11:19:21.095 INFO 9864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-10-13 11:19:21.307 INFO 9864 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-10-13 11:19:21.463 INFO 9864 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-10-13 11:19:21.479 INFO 9864 --- [ main] hello.Application : Started Application in 6.497 seconds (JVM running for 7.83)
2016-10-13 11:21:46.570 INFO 9864 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-10-13 11:21:46.570 INFO 9864 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-10-13 11:21:46.622 INFO 9864 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 51 ms
表示启动成功,这是就可以访问了 http://localhost:8080/greeting?name=xxb
会出现如下结果:
{"id":3,"content":"Hello,xuxiaobo!"}
这是一个纯java的项目,不需要启动tomcat也可以执行访问
首先你需要建立一个基本的项目,你可以使用任何你喜欢的方式去构造Spring项目,这里使用的是Maven.如果你不熟悉Maven的话请移步 Building Java Projects with Maven.
创建项目目录结构
在你所选的项目目录中,创建如下的子目录结构;例如在unix系统中使用mkdir -p src/main/java/hello。
└── src
└── main
└── java
└── hello
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Spring Boot的maven插件提供了很多便利的特性:
- 它包含了路径中的所有jar文件,使用“über-jar”。它使得执行和转换服务非常便利。
它查询
public static void main()
方法去标志为一个可执行的类- 它提供了一个内置的匹配Spring boot 依赖的版本,你可以选择任何你希望的版本,但是默认情况下它会选择Boot的版本设置变量。
【Spring Boot && Spring Cloud系列】构建Springboot项目 实现restful风格接口的更多相关文章
- 【Spring】构建Springboot项目 实现restful风格接口
项目代码如下: package hello; import org.springframework.boot.SpringApplication; import org.springframework ...
- Spring Boot 学习(一) 快速搭建SpringBoot 项目
快速搭建一个 Spring Boot 项目 部分参考于<深入实践Spring Boot>.<Spring实战 第四版>与程序猿DD的有关博客. 参考(嘟嘟独立博客):http: ...
- Spring Boot学习记录02_构建SpringBoot工程_通过idea构建
1.通过idea新建工程 2.Initial Service Url指向的地址就是Spring官方提供的Spring Initializr工具地址 3.结合情况进行设置 4.这里我选择的版本是1.5. ...
- Spring Boot 2.0系列文章(五):Spring Boot 2.0 项目源码结构预览
关注我 转载请务必注明原创地址为:http://www.54tianzhisheng.cn/2018/04/15/springboot2_code/ 项目结构 结构分析: Spring-boot-pr ...
- 新书上线:《Spring Boot+Spring Cloud+Vue+Element项目实战:手把手教你开发权限管理系统》,欢迎大家买回去垫椅子垫桌脚
新书上线 大家好,笔者的新书<Spring Boot+Spring Cloud+Vue+Element项目实战:手把手教你开发权限管理系统>已上线,此书内容充实.材质优良,乃家中必备垫桌脚 ...
- Cola Cloud 基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台
Cola Cloud 基于 Spring Boot, Spring Cloud 构建微服务架构企业级开发平台: https://gitee.com/leecho/cola-cloud
- Spring Boot 2.x 系列教程:WebFlux 系列教程大纲(一)
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! WebFlux 系列教程大纲 一.背景 大家都知道,Sprin ...
- Java面试题(Spring Boot/Spring Cloud篇)
Spring Boot/Spring Cloud 104.什么是 spring boot? SpringBoot是一个框架,一种全新的编程规范,他的产生简化了框架的使用,所谓简化是指简化了Spring ...
- Spring Boot中使用Swagger2构建API文档
程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...
随机推荐
- UVA 11019 Matrix Matcher 矩阵匹配器 AC自动机 二维文本串查找二维模式串
链接:https://vjudge.net/problem/UVA-11019lrjP218 matrix matcher #include<bits/stdc++.h> using na ...
- iOS边练边学--介绍布局的三种方法
使用代码实现Autolayout的方法1- 创建约束 +(id)constraintWithItem:(id)view1attribute:(NSLayoutAttribute)attr1relate ...
- Java-DBCP连接池
创建项目: 导入jar包: 参见上图. JDBCConn.java获取数据源类: package com.gordon.jdbcconn; import java.io.InputStream; im ...
- CentOS安装ssh服务
yum search ssh yum install openssh-server service sshd status [编辑]艺搜参考 http://www.cnblogs.com/eastso ...
- FroalaEditor使用方法汇总
最近在整个移动端富文本编辑器.写完后,在安卓端表现良好,在苹果端测试让我直吐血.开始在网上找了一圈,也没发现自己中意的那款. 今天无意中发现了FroalaEditor,经过在移动端测试一番,表现的好的 ...
- R工具包
直到12月初在微软技术大会,看到我软的工程师演示R的使用,我就震惊了,然后最近在网上到处了解和爬一些R的资料,看着看着就入迷了,这就是个大宝库了,以前怎么没发现,看来还是太狭隘了.直到前几天我看到这个 ...
- ElasticSearch使用代码
package elasticsearch01; import static org.junit.Assert.*; import java.util.HashMap; import java.uti ...
- 关于Cocos2d-x数据类型的使用
常用的是三种数据类型,Value,Vector,Map,翻译成中文就是值,数组,字典.其中字典的意思就是拿着某个关键字去这个数据结构里面找相应的对应的数据. //Value数据类型 Value int ...
- selenium测试(Java)--多表单切换(十二)
采用下面的例子来编写用例 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type& ...
- IoC就是IoC,不是什么技术,与GoF一样,是一种 设计模式。
IoC就是IoC,不是什么技术,与GoF一样,是一种 设计模式. Interface Driven Design接口驱动,接口驱动有很多好处,可以提供不同灵活的子类实现,增加代码稳定和健壮性等等,但是 ...