码迷,mamicode.com
首页 > 编程语言 > 详细

【Spring】构建Springboot项目 实现restful风格接口

时间:2016-10-13 13:54:48      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

项目代码如下:

 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:\rest风格的apring项目\restSpringDemo1)
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也可以执行访问

First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Maven is included here. If you’re not familiar with Maven, refer to Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── 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>

The Spring Boot Maven plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.

  • It searches for the public static void main() method to flag as a runnable class.

  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

 

【Spring】构建Springboot项目 实现restful风格接口

标签:

原文地址:http://www.cnblogs.com/dream-to-pku/p/5955862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!