zoukankan      html  css  js  c++  java
  • 【Spring Boot && Spring Cloud系列】构建Springboot项目 实现restful风格接口

    项目代码如下:

     1 package hello;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 
     6 @SpringBootApplication  // same as @Configuration @EnableAutoConfiguration @ComponentScan
     7 
     8 public class Application {
     9 
    10     public static void main(String[] args) {
    11          SpringApplication.run(Application.class, args);
    12     }
    13 
    14 }
     1 package hello;
     2 
     3 public class Greeting {
     4 private  long id;
     5 private  String content;
     6 public Greeting(long id, String content) {
     7     super();
     8     this.id = id;
     9     this.content = content;
    10 }
    11 public long getId() {
    12     return id;
    13 }
    14 public void setId(long id) {
    15     this.id = id;
    16 }
    17 public String getContent() {
    18     return content;
    19 }
    20 public void setContent(String content) {
    21     this.content = content;
    22 }
    23 
    24 }
     1 package hello;
     2 
     3 import java.util.concurrent.atomic.AtomicLong;
     4 
     5 import org.springframework.web.bind.annotation.RequestMapping;
     6 import org.springframework.web.bind.annotation.RequestParam;
     7 import org.springframework.web.bind.annotation.RestController;
     8 
     9 @RestController // shorthand for @Controller and @ResponseBody rolled together
    10 public class GreetingController {
    11 
    12     private static final String template="Hello,%s!";
    13     private final AtomicLong counter=new AtomicLong();
    14     
    15     @RequestMapping("/greeting")
    16     public Greeting greeting(@RequestParam(value="name",defaultValue="World")String name){
    17         System.out.println("-------------------------");
    18         return new Greeting(counter.incrementAndGet(),String.format(template, name));
    19     }
    20 }
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5 
     6     <groupId>com.slp</groupId>
     7     <artifactId>restSpringDemo1</artifactId>
     8     <version>0.1.0</version>
     9 
    10     <parent>
    11         <groupId>org.springframework.boot</groupId>
    12         <artifactId>spring-boot-starter-parent</artifactId>
    13         <version>1.4.1.RELEASE</version>
    14     </parent>
    15 
    16     <dependencies>
    17         <dependency>
    18             <groupId>org.springframework.boot</groupId>
    19             <artifactId>spring-boot-starter-web</artifactId>
    20         </dependency>
    21         <dependency>
    22             <groupId>org.springframework.boot</groupId>
    23             <artifactId>spring-boot-starter-test</artifactId>
    24             <scope>test</scope>
    25         </dependency>
    26         <dependency>
    27             <groupId>com.jayway.jsonpath</groupId>
    28             <artifactId>json-path</artifactId>
    29             <scope>test</scope>
    30         </dependency>
    31     </dependencies>
    32 
    33     <properties>
    34         <java.version>1.8</java.version>
    35     </properties>
    36 
    37 
    38     <build>
    39         <plugins>
    40             <plugin>
    41                 <groupId>org.springframework.boot</groupId>
    42                 <artifactId>spring-boot-maven-plugin</artifactId>
    43             </plugin>
    44         </plugins>
    45     </build>
    46 
    47     <repositories>
    48         <repository>
    49             <id>spring-releases</id>
    50             <url>https://repo.spring.io/libs-release</url>
    51         </repository>
    52     </repositories>
    53     <pluginRepositories>
    54         <pluginRepository>
    55             <id>spring-releases</id>
    56             <url>https://repo.spring.io/libs-release</url>
    57         </pluginRepository>
    58     </pluginRepositories>
    59 </project>

    在Application.java中run as java application 出现:

     1  .   ____          _            __ _ _
     2  /\ / ___'_ __ _ _(_)_ __  __ _    
     3 ( ( )\___ | '_ | '_| | '_ / _` |    
     4  \/  ___)| |_)| | | | | || (_| |  ) ) ) )
     5   '  |____| .__|_| |_|_| |_\__, | / / / /
     6  =========|_|==============|___/=/_/_/_/
     7  :: Spring Boot ::        (v1.4.1.RELEASE)
     8 
     9 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:
    est风格的apring项目
    estSpringDemo1)
    10 2016-10-13 11:19:16.525  INFO 9864 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
    11 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
    12 2016-10-13 11:19:19.691  INFO 9864 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
    13 2016-10-13 11:19:19.710  INFO 9864 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
    14 2016-10-13 11:19:19.710  INFO 9864 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.35
    15 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.
    16 2016-10-13 11:19:20.148  INFO 9864 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    17 2016-10-13 11:19:20.148  INFO 9864 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3451 ms
    18 2016-10-13 11:19:20.382  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
    19 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    20 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    21 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    22 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    23 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
    24 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)
    25 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)
    26 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)
    27 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]
    28 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]
    29 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]
    30 2016-10-13 11:19:21.307  INFO 9864 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    31 2016-10-13 11:19:21.463  INFO 9864 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    32 2016-10-13 11:19:21.479  INFO 9864 --- [           main] hello.Application                        : Started Application in 6.497 seconds (JVM running for 7.83)
    33 2016-10-13 11:21:46.570  INFO 9864 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
    34 2016-10-13 11:21:46.570  INFO 9864 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
    35 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的版本设置变量。
  • 相关阅读:
    图像相似度
    二维数组 问题 E: 计算鞍点
    Uva
    Uva
    Uva
    Uva
    Uva
    Uva
    Uva
    【转载】2015 Objective-C 三大新特性 | 干货
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/5955862.html
Copyright © 2011-2022 走看看