Share an example tutorial on developing Restful programs using Spring Boot
本篇文章主要介绍了详解使用Spring Boot开发Restful程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
一、简介
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
多年以来,Spring IO平台饱受非议的一点就是大量的XML配置以及复杂的依赖管理。在去年的SpringOne 2GX会议上,Pivotal的CTO Adrian Colyer回应了这些批评,并且特别提到该平台将来的目标之一就是实现免XML配置的开发体验。Boot所实现的功能超出了这个任务的描述,开发人员不仅不再需要编写XML,而且在一些场景中甚至不需要编写繁琐的import语句。在对外公开的beta版本刚刚发布之时,Boot描述了如何使用该框架在140个字符内实现可运行的web应用,从而获得了极大的关注度,该样例发表在tweet上。
Spring Boot不生成代码,且完全不需要XML配置。其主要目标如下:
为所有的Spring开发工作提供一个更快、更广泛的入门经验。
开箱即用,你也可以通过修改默认值来快速满足你的项目的需求。
提供了一系列大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。
二、开发环境准备
IDE:IntelliJ IDEA
JDK:1.8
Maven
数据库:MySQL
我将以一个用户积分系统为例,开发一个Restful风格的服务端
三、第一个Restful程序
1.新建一个普通Maven工程
创建项目完成后目录结构如下图所示
2.在POM文件中加入对Spring-Boot的依赖
<?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 maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bluecoffee</groupId> <artifactId>mapp</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3.新建一个RestController来接收客户端的请求,我们来模拟一个登录请求
package com.yepit.mapp.rest; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.*; /** * Created by qianlong on 16/7/20. */ @RestController public class UserController { @RequestMapping(value = "/users/{username}",method = RequestMethod.GET,consumes="application/json") public String getUser(@PathVariable String username, @RequestParam String pwd){ return "Welcome,"+username; }}
关键字@RestController代表这个类是用Restful风格来访问的,如果是普通的WEB页面访问跳转时,我们通常会使用@Controller
value = "/users/{username}" 代表访问的URL是"http://host:PORT/users/实际的用户名"
method = RequestMethod.GET 代表这个HTTP请求必须是以GET方式访问
consumes="application/json" 代表数据传输格式是json
@PathVariable将某个动态参数放到URL请求路径中
@RequestParam指定了请求参数名称
4.新建启动Restful服务端的启动类
package com.yepit.mapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by qianlong on 16/7/20. */ @SpringBootApplication public class MappRunApplication { public static void main(String[] args) { SpringApplication.run(MappRunApplication.class, args); } }
5.执行MappRunApplication的Main方法启动Restful服务,可以看到控制台有如下输出
. _ _ _ /\\\\ / _'_ _ _(_)_ _ \\ \\ \\ \\ ( ( )\\_ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ _)| |_)| | | | | || (_| | ) ) ) ) ' || .|_| |_|_| |_\\, | / / / / =========|_|==============|_/=/_/_/_/ :: Spring Boot :: (v1.3.3.RELEASE) 2016-07-20 16:49:43.334 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : Starting MappRunApplication on bogon with PID 2106 (/Users/qianlong/workspace/spring-boot-samples/target/classes started by qianlong in /Users/qianlong/workspace/spring-boot-samples) 2016-07-20 16:49:43.338 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : No active profile set, falling back to default profiles: default 2016-07-20 16:49:43.557 INFO 2106 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@543e710e: startup date [Wed Jul 20 16:49:43 CST 2016]; root of context hierarchy 2016-07-20 16:49:44.127 INFO 2106 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]] 2016-07-20 16:49:44.658 INFO 2106 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2016-07-20 16:49:44.672 INFO 2106 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2016-07-20 16:49:44.673 INFO 2106 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.32 2016-07-20 16:49:44.759 INFO 2106 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2016-07-20 16:49:44.759 INFO 2106 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1207 ms 2016-07-20 16:49:44.972 INFO 2106 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2016-07-20 16:49:44.977 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2016-07-20 16:49:44.978 INFO 2106 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2016-07-20 16:49:45.184 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@543e710e: startup date [Wed Jul 20 16:49:43 CST 2016]; root of context hierarchy 2016-07-20 16:49:45.251 INFO 2106 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/users],methods=[GET],consumes=[application/json]}" onto public java.lang.String com.yepit.mapp.rest.UserController.getUser(java.lang.String,java.lang.String) 2016-07-20 16:49:45.253 INFO 2106 --- [ 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-07-20 16:49:45.254 INFO 2106 --- [ 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-07-20 16:49:45.275 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-20 16:49:45.275 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-20 16:49:45.306 INFO 2106 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-20 16:49:45.380 INFO 2106 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2016-07-20 16:49:45.462 INFO 2106 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2016-07-20 16:49:45.467 INFO 2106 --- [ main] com.yepit.mapp.MappRunApplication : Started MappRunApplication in 2.573 seconds (JVM running for 3.187)
我们可以看到服务器是Tomcat,端口为8080
6.验证
推荐大家使用Google的Postman插件来模拟请求
在发起请求前,请注意需要在Headers中设置Content-Type为application/json
到此一个基本的Restful风格的服务端就已经完成了,全部编码时间不会超过5分钟!
【相关推荐】
2. Detailed explanation of Spring and Hibernate code for Java transaction management learning
3. Detailed explanation of the seven return methods supported by spring mvc
4. Detailed explanation of Spring’s enhanced implementation examples based on Aspect
5. PHPRPC for Java Spring examples
6. Java Spring mvc operates Redis and Redis cluster
7. Detailed tutorial on using Elasticsearch in spring
The above is the detailed content of Share an example tutorial on developing Restful programs using Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![Windows ISO file too large BootCamp error [Fixed]](https://img.php.cn/upload/article/000/887/227/170831702395455.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
If you get the error message "The Windows ISO file is too large" when using BootCampAssistant on a Mac computer, this may be because the ISO file size exceeds the limit supported by BootCampAssistant. The solution to this problem is to use other tools to compress the ISO file size to ensure that it can be processed in BootCamp Assistant. BootCampAssistant is a convenient tool provided by Apple for installing and running Windows operating system on Mac computers. It helps users set up a dual-boot system, allowing them to easily choose to use MacOS or Wind at startup

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

Java implements scheduled tasks In the library that comes with Jdk, there are two ways to implement scheduled tasks, one is Timer, and the other is ScheduledThreadPoolExecutor. When Timer+TimerTask creates a Timer, it creates a thread, which can be used to schedule TimerTask tasks. Timer has four construction methods, and you can specify the name of the Timer thread and whether to set it as a daemon thread. The default name is Timer-number, and the default is not a daemon thread. There are three main methods: cancel(): terminate task scheduling, cancel all currently scheduled tasks, running tasks will not be affected purge(): remove tasks from the task queue

SpringBoot and SpringCloud are both extensions of Spring Framework that help developers build and deploy microservice applications faster, but they each have different purposes and functions. SpringBoot is a framework for quickly building Java applications, allowing developers to create and deploy Spring-based applications faster. It provides a simple, easy-to-understand way to build stand-alone, executable Spring applications

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in Java, spring has slowly begun to abandon xml configuration since it was updated to version 2.5, and more annotations are used to control the spring framework.
