Spring Boot系列——Hello World

来源:互联网 发布:上海淘车网络骗局 编辑:程序博客网 时间:2024/05/21 06:58

在这个章节,先来一个Hello World的Web应用,用以对Spring Boot做一个初步的了解。

我打算使用Maven和Eclipse开始我们的Hello World。

准备

Spring Boot当前最新版本为1.3.3.RELEASE,按照官方文档指引,首先确保安装了JDK 1.6+、Maven 3.2+。

以Windows为例,在命令行输入命令,如下:

C:\Users\lewis>java -versionjava version "1.8.0_74"Java(TM) SE Runtime Environment (build 1.8.0_74-b02)Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)
C:\Users\lewis>mvn --vApache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)Maven home: D:\Apps\DevpApp\Apache\apache-maven-3.3.9Java version: 1.8.0_74, vendor: Oracle CorporationJava home: D:\Apps\DevpApp\Java\jdk1.8.0_74\jreDefault locale: zh_CN, platform encoding: GBKOS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

创建Maven Project

首先通过Eclipse创建一个Maven Project,其pom文件如下:

<?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.learn.springboot</groupId>    <artifactId>gs-spring-boot</artifactId>    <version>0.1.0</version></project>

添加spring-boot-starter-parent

Spring Boot提供了一系列starter POMs,这个在前一篇文章有介绍。其中spring-boot-starter-parent是一个特殊的starter,它提供了很多有用的Maven默认设置,重要的是它还包括一个dependency-management。

在pom文件中加入如下代码:

    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.3.3.RELEASE</version>    </parent>

添加依赖

既然是Web应用,那么为我们的项目添加spring-boot-starter-web依赖。

在pom文件中加入如下代码:

    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>    </dependencies>

编写代码

为完成Hello World的Web应用,我们需要一个Java文件。

在src/main/java目录下,创建一个类SampleController,代码如下:

package org.learn.springboot.gs;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@EnableAutoConfigurationpublic class SampleController {    @RequestMapping("/")    @ResponseBody    String home() {        return "Hello World!";    }    public static void main(String[] args) throws Exception {        SpringApplication.run(SampleController.class, args);    }}

运行

到这里,所有工作就完成了,剩下就是运行看效果了。

在Eclipse中启动你的SampleController类,控制台会输出信息:

  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.3.3.RELEASE)2016-03-15 22:58:41.200  INFO 2636 --- [           main] o.learn.springboot.gs.SampleController   : Starting SampleController on DESKTOP-RSSEC8O with PID 2636 (E:\work\project\learn-spring-boot\gs-spring-boot\target\classes started by lewis in E:\work\project\learn-spring-boot\gs-spring-boot)2016-03-15 22:58:41.216  INFO 2636 --- [           main] o.learn.springboot.gs.SampleController   : No active profile set, falling back to default profiles: default2016-03-15 22:58:41.341  INFO 2636 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@df27fae: startup date [Tue Mar 15 22:58:41 CST 2016]; root of context hierarchy2016-03-15 22:58:42.403  INFO 2636 --- [           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-03-15 22:58:43.636  INFO 2636 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2016-03-15 22:58:43.677  INFO 2636 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat2016-03-15 22:58:43.677  INFO 2636 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.322016-03-15 22:58:43.896  INFO 2636 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext2016-03-15 22:58:43.896  INFO 2636 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2586 ms2016-03-15 22:58:44.318  INFO 2636 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]2016-03-15 22:58:44.318  INFO 2636 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]2016-03-15 22:58:44.318  INFO 2636 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2016-03-15 22:58:44.318  INFO 2636 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]2016-03-15 22:58:44.318  INFO 2636 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]2016-03-15 22:58:44.728  INFO 2636 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@df27fae: startup date [Tue Mar 15 22:58:41 CST 2016]; root of context hierarchy2016-03-15 22:58:44.838  INFO 2636 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String org.learn.springboot.gs.SampleController.home()2016-03-15 22:58:44.854  INFO 2636 --- [           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-03-15 22:58:44.854  INFO 2636 --- [           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-03-15 22:58:44.947  INFO 2636 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-03-15 22:58:44.947  INFO 2636 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-03-15 22:58:45.026  INFO 2636 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-03-15 22:58:45.244  INFO 2636 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup2016-03-15 22:58:45.401  INFO 2636 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2016-03-15 22:58:45.416  INFO 2636 --- [           main] o.learn.springboot.gs.SampleController   : Started SampleController in 5.17 seconds (JVM running for 6.246)

在浏览器中打开localhost:8080,页面会带给你惊喜:

Hello World!

创建可执行的jar包

再一次惊喜,把这些变成一个可执行的jar包,并且发布生产环境可独立运行。

在pom文件中加入如下代码:

    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build>

然后,在命令行执行mvn package

[INFO] Scanning for projects...[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building gs-spring-boot 0.1.0[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- ------[INFO] [INFO] --- maven-jar-plugin:2.5:jar (default-jar) @ gs-spring-boot ---[INFO] Building jar: E:\work\project\learn-spring-boot\gs-spring-boot\target\gs-spring-boot-0.1.0.jar[INFO] [INFO] --- spring-boot-maven-plugin:1.3.3.RELEASE:repackage (default) @ gs-spring-boot ---[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------

在工程的target目录下,你会看到gs-spring-boot-0.1.0.jar,大概12.8M,因为这个jar包包含了所有的依赖lib。

通过压缩软件或者在命令行输入命令java tvf gs-spring-boot-0.1.0.jar,你可以进一步研究下这个jar包的内部结构。

在命令行,进入target目录,输入命令java -jar,如下:

E:\work\project\learn-spring-boot\gs-spring-boot\target>java -jar gs-spring-boot-0.1.0.jar  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.3.3.RELEASE)2016-03-15 23:20:47.934  INFO 5252 --- [           main] o.learn.springboot.gs.SampleController   : Starting SampleController v0.1.0 on DESKTOP-RSSEC8O with PID 5252 (E:\work\project\learn-spring-boot\gs-spring-boot\target\gs-spring-boot-0.1.0.jar started by lewis in E:\work\project\learn-spring-boot\gs-spring-boot\target)2016-03-15 23:20:47.934  INFO 5252 --- [           main] o.learn.springboot.gs.SampleController   : No active profile set, falling back to default profiles: default2016-03-15 23:20:47.996  INFO 5252 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@29159081: startup date [Tue Mar 15 23:20:47 CST 2016]; root of context hierarchy......2016-03-15 23:20:52.082  INFO 5252 --- [           main] o.learn.springboot.gs.SampleController   : Started SampleController in 4.679 seconds (JVM running for 5.326)

在浏览器中打开localhost:8080,页面会再一次带给你惊喜。

0 0
原创粉丝点击