zoukankan      html  css  js  c++  java
  • 使用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:SoftwarefolderIDEMyEclipseWorkSpaceSSMSpringBoot 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>
    

    这里需要注意的是,版本要匹配不然会报错。 

     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    1046 Shortest Distance (20 分)(模拟)
    1004. Counting Leaves (30)PAT甲级真题(bfs,dfs,树的遍历,层序遍历)
    1041 Be Unique (20 分)(hash散列)
    1036 Boys vs Girls (25 分)(查找元素)
    1035 Password (20 分)(字符串处理)
    1044 Shopping in Mars (25 分)(二分查找)
    onenote使用小Tip总结^_^(不断更新中...)
    1048 Find Coins (25 分)(hash)
    三个故事
    领导者的举止
  • 原文地址:https://www.cnblogs.com/caopt/p/8303456.html
Copyright © 2011-2022 走看看