使用spring boot 在MyEclipse上創建一個簡單的應用程序


Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。

 

Spring Boot特點

1. 創建獨立的Spring應用程序
2. 嵌入的Tomcat,無需部署WAR文件
3. 簡化Maven配置
4. 自動配置Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6. 絕對沒有代碼生成和對XML沒有要求配置
 
環境准備:
  Myeclipse
  jdk1.7及以上
  maven 3.0以上
1、首先建一個maven項目,pom.xml文件內容如下代碼所示:
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.cpt</groupId>
    <artifactId>SpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
        <relativePath />
    </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>
    </dependencies>

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


</project>

2、保存之后靜靜等待依賴包下載完畢,接下來創建一個java類,

在src/main/java下創建一個TestSpringBoot.java類,里面添加代碼如下:

 
package controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class TestSpringBoot {
    @RequestMapping("/")
    public String firstSpringBoot() {
        return "Hello World!";
    }
    
    public static void main(String[] args){
        SpringApplication.run(TestSpringBoot.class, args);
    }
}

3、直接運行main方法;它會啟動內置的tomcat服務:啟動后如下所示:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.2.5.RELEASE)

2018-01-17 16:20:06.722  INFO 6028 --- [           main] controller.TestSpringBoot                : Starting TestSpringBoot on 0DYF9DI9DPNWES6 with PID 6028 (started by Administrator in D:\Softwarefolder\IDE\MyEclipse\WorkSpace\SSM\SpringBoot Maven Webapp)
2018-01-17 16:20:06.831  INFO 6028 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5fd91a7a: startup date [Wed Jan 17 16:20:06 CST 2018]; root of context hierarchy
2018-01-17 16:20:08.077  INFO 6028 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': 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]]
2018-01-17 16:20:09.743  INFO 6028 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9000 (http)
2018-01-17 16:20:10.247  INFO 6028 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-01-17 16:20:10.249  INFO 6028 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.23
2018-01-17 16:20:10.485  INFO 6028 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-01-17 16:20:10.485  INFO 6028 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3659 ms
2018-01-17 16:20:11.820  INFO 6028 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-17 16:20:11.827  INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-17 16:20:11.827  INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-17 16:20:12.187  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5fd91a7a: startup date [Wed Jan 17 16:20:06 CST 2018]; root of context hierarchy
2018-01-17 16:20:12.343  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String controller.TestSpringBoot.firstSpringBoot()
2018-01-17 16:20:12.344  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String controller.TestSpringBoot.loginGet()
2018-01-17 16:20:12.344  INFO 6028 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto public java.lang.String controller.TestSpringBoot.loginPost()
2018-01-17 16:20:12.348  INFO 6028 --- [           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)
2018-01-17 16:20:12.348  INFO 6028 --- [           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)
2018-01-17 16:20:12.407  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-17 16:20:12.407  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-17 16:20:12.482  INFO 6028 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-01-17 16:20:12.619  INFO 6028 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-01-17 16:20:12.747  INFO 6028 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9000 (http)
2018-01-17 16:20:12.750  INFO 6028 --- [           main] controller.TestSpringBoot                : Started TestSpringBoot in 6.666 seconds (JVM running for 7.24)

3、在網頁上可輸入地址localhost:8080/即可訪問到firstSpringBoot()方法,在頁面上顯示Hello word,

(如果報錯端口被占用的話可以修改內置Tomcat的端口,詳情連接 http://www.cnblogs.com/caopt/p/8303662.html)

4、這是一個簡單應用程序,可是為什么它運行main方法就可以了呢,讓我們從源碼分析一下:

運行main方法之后 SpringApplication會運行他的run方法,看下源碼

 

/**
     * Static helper that can be used to run a {@link SpringApplication} from the
     * specified source using default settings.
     * @param source the source to load
     * @param args the application arguments (usually passed from a Java main method)
     * @return the running {@link ApplicationContext}
     */
    public static ConfigurableApplicationContext run(Object source, String... args) {
        return run(new Object[] { source }, args);
    }

    /**
     * Static helper that can be used to run a {@link SpringApplication} from the
     * specified sources using default settings and user supplied arguments.
     * @param sources the sources to load
     * @param args the application arguments (usually passed from a Java main method)
     * @return the running {@link ApplicationContext}
     */
    public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
        return new SpringApplication(sources).run(args);
    }

 

1、它根據傳過來的類會創建一個Spring應用上下文(Application Context)(通過映射的方式找到要找的東西)。另一方面它會掃描當前應用類路徑上的依賴,例如本例中發現spring-webmvc(由 spring-boot-starter-web傳遞引入)在類路徑中,那么Spring Boot會判斷這是一個Web應用,並啟動一個內嵌的Servlet容器(默認是Tomcat)用於處理HTTP請求。

 

 2、當發生請求過來之后,Spring Web Mvc框架會將Servlet容器里收到的HTTP請求根據路徑分發給對應的 @Controller類進行處理, @RestController是一類特殊的 @Controller,它的返回值直接作為HTTP Response的Body部分返回給瀏覽器。
 3、多個url路徑如下代碼
 
package controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class TestSpringBoot {
    
    @RequestMapping(value = "/TestGet", method = RequestMethod.GET)
    public String testGet() {
        return "Hello Get";
    }

    @RequestMapping(value = "/TestPost", method = RequestMethod.POST)
    public String testPost() {
        return "Hello Post";
    }
    @RequestMapping("/")
    public String firstSpringBoot() {
        return "Hello World!";
    }
    
    public static void main(String[] args){
        SpringApplication.run(TestSpringBoot.class, args);
    }
}

 4、springBoot對調試支持很好,修改之后可以實時生效,需要添加以下的配置:

 
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
   </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
   </plugins>
</build>

這里需要注意的是,版本要匹配不然會報錯。 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM