Spring Boot【1.ハロルド】

17531 ワード

1.使用要求2.POM.xml 3.コード4.包装と運転
本バージョン:Spring Boot 1.5.7.RELEASE
1.使用要求
オススメjava 8(1.6/1.7 Springboot 1.x.xも使えます)、Maven(3.2+)
Spring Boot 2.0.0.BUILD-SNAPSHOT requires Java 8 and Spring Framework 5.0.0.RELEASE or above;
Explicit build support is provided for Maven (3.2+), and Gradle 4.
#    
$ java -version
$ mvn -v
2.POM.xml

    4.0.0
    com.top.test.springboot
    test-springboot
    0.0.1-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.7.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

  • SpringBootは多くのStarter POMを提供し、Jarsを簡略化するためにclassipathに追加する動作
  • を提供する.
  • spring-boot-starter-parentはparentノードとして、Mavenのデフォルト設定とバージョン制御を提供していますので、望む(「blesed」)の依存はversionフラグ
  • を省略することができます.
  • spring-boot-starter-parent自体は任意の依存性を導入しない(mvn dependency:tree)
  • 他のStarter POMも特定のタイプのアプリケーションを開発するために必要な依存性だけを提供し、必要に応じて
  • を導入する.
  • spring-boot-starter-web依存ツリーには、springboot、spring-webmvc、tomcat、jackson、hibernal-validatorなどの
  • が含まれています.
    3.コード
    package com.top.test.springboot;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController//@ResponseBody + @Controller
    public class HelloController {
        @RequestMapping(value="/hello")
        public String helloWorld() {
            return "hello world!";
        }
    }
    
    package com.top.test.controller;
    
    import java.util.Arrays;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * @SpringBootApplication  : @Configuration + @ComponentScan + @EnableAutoConfiguration
     *   @Configuration      ;@ComponentScan       /  ;@EnableAutoConfiguration      
     */
    //@SpringBootApplication
    @EnableAutoConfiguration
    @ComponentScan(basePackages="com.top.test")//          
    public class HelloApplication {
        
        public static void main(String[] args) {
            SpringApplication.run(HelloApplication.class, args);
        }
        
        //  app      springboot     bean,     
        @Bean
        public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
            final String[] beanNames = ctx.getBeanDefinitionNames();
            return new CommandLineRunner() {
                @Override
                public void run(String... args) throws Exception {
                    System.out.println("Let's inspect the beans provided by Spring Boot:");
                    Arrays.sort(beanNames);
                    for (String beanName : beanNames) {
                        System.out.println(beanName);
                    }
                }
            };
        }
    }
    
  • Auto-configrationはStarter POMとよく協力して使うことができますが、両者は直接連絡していません.Starter POM以外のjarは依存しています.Spring Bootは依然として自動配置
  • に最善を尽くします.
  • main方法は、アプリケーションの入口であり、SpringBootのSpringApplication類の呼び出しを依頼するrun()であり、アプリケーションを起動する(自動的に配置されたTomcatを起動することを含む)
  • .
    4.運転
    - 1. project   ,     mvn spring-boot:run
    - 2.  IDE:  main  Run as Java Application ||   maven build(   1) 
    - 3.   jar, java -jar xxx.jar
    
    ブラウザのアクセス:http://localhost:8080/hello
    このうち、jarとして包装して実行します.spring-boot-maven-pluginプラグインを利用します.
    starter parentにはパッケージの配置があります.spring-boot-starter-parentを使わないとPOM.xmlにパッケージを自分で配置しなければなりません.ここでstarter parentを使っています.spring-boot-maven-pluginプラグインを導入すればいいです.
     #    
    $ mvn package
    
    #      
    [INFO] Scanning for projects...
    [INFO]                                                                         
    [INFO] ------------------------------------------------------------------------
    [INFO] Building test-springboot 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test-springboot ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] Copying 0 resource
    [INFO] Copying 0 resource
    [INFO] 
    [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test-springboot ---
    [INFO] Nothing to compile - all classes are up to date
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test-springboot ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] Copying 0 resource
    [INFO] 
    [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test-springboot ---
    [INFO] Changes detected - recompiling the module!
    [INFO] 
    [INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ test-springboot ---
    [INFO] 
    [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ test-springboot ---
    [INFO] Building jar: /home/yuzhou/personalDev/workspace/test-springboot/target/test-springboot-0.0.1-SNAPSHOT.jar
    [INFO] 
    [INFO] --- spring-boot-maven-plugin:1.5.7.RELEASE:repackage (default) @ test-springboot ---
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    もう一つのtest-springboot-0.0.1-NAPSHOT.jar.originalはSpring Bootを再包装する前に、Mavenが作成したオリジナルjarファイルです.
    #  jar  
    $ jar tvf test-springboot-0.0.1-SNAPSHOT.jar
    
    #  jar
    $ java -jar test-springboot-0.0.1-SNAPSHOT.jar 
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v1.5.7.RELEASE)
    
    2017-10-12 18:16:27.774  INFO 12580 --- [           main] c.top.test.controller.HelloApplication   : Starting HelloApplication v0.0.1-SNAPSHOT on yuzhou with PID 12580 (/home/yuzhou/personalDev/workspace/test-springboot/target/test-springboot-0.0.1-SNAPSHOT.jar started by yuzhou in /home/yuzhou/personalDev/workspace/test-springboot/target)
    2017-10-12 18:16:27.777  INFO 12580 --- [           main] c.top.test.controller.HelloApplication   : No active profile set, falling back to default profiles: default
    2017-10-12 18:16:27.818  INFO 12580 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6659c656: startup date [Thu Oct 12 18:16:27 CST 2017]; root of context hierarchy
    2017-10-12 18:16:28.831  INFO 12580 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
    2017-10-12 18:16:28.842  INFO 12580 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2017-10-12 18:16:28.843  INFO 12580 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.20
    2017-10-12 18:16:28.912  INFO 12580 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2017-10-12 18:16:28.912  INFO 12580 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1096 ms
    2017-10-12 18:16:28.997  INFO 12580 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
    2017-10-12 18:16:29.001  INFO 12580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2017-10-12 18:16:29.001  INFO 12580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2017-10-12 18:16:29.001  INFO 12580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2017-10-12 18:16:29.001  INFO 12580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2017-10-12 18:16:29.297  INFO 12580 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6659c656: startup date [Thu Oct 12 18:16:27 CST 2017]; root of context hierarchy
    2017-10-12 18:16:29.368  INFO 12580 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.top.test.springboot.HelloController.helloWorld()
    2017-10-12 18:16:29.370  INFO 12580 --- [           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)
    2017-10-12 18:16:29.371  INFO 12580 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2017-10-12 18:16:29.401  INFO 12580 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2017-10-12 18:16:29.401  INFO 12580 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2017-10-12 18:16:29.440  INFO 12580 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2017-10-12 18:16:29.539  INFO 12580 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2017-10-12 18:16:29.581  INFO 12580 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    Let's inspect the beans provided by Spring Boot:
    basicErrorController
    beanNameHandlerMapping
    beanNameViewResolver
    characterEncodingFilter
    commandLineRunner
    conventionErrorViewResolver
    defaultServletHandlerMapping
    defaultValidator
    defaultViewResolver
    dispatcherServlet
    dispatcherServletRegistration
    duplicateServerPropertiesDetector
    embeddedServletContainerCustomizerBeanPostProcessor
    error
    errorAttributes
    errorPageCustomizer
    errorPageRegistrarBeanPostProcessor
    faviconHandlerMapping
    faviconRequestHandler
    handlerExceptionResolver
    helloApplication
    helloController
    hiddenHttpMethodFilter
    httpPutFormContentFilter
    httpRequestHandlerAdapter
    jacksonObjectMapper
    jacksonObjectMapperBuilder
    jsonComponentModule
    localeCharsetMappingsCustomizer
    mappingJackson2HttpMessageConverter
    mbeanExporter
    mbeanServer
    messageConverters
    methodValidationPostProcessor
    multipartConfigElement
    multipartResolver
    mvcContentNegotiationManager
    mvcConversionService
    mvcPathMatcher
    mvcResourceUrlProvider
    mvcUriComponentsContributor
    mvcUrlPathHelper
    mvcValidator
    mvcViewResolver
    objectNamingStrategy
    org.springframework.boot.autoconfigure.AutoConfigurationPackages
    org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
    org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
    org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
    org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
    org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
    org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
    org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration
    org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
    org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
    org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
    org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
    org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration
    org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
    org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
    org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration
    org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration
    org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
    org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration
    org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
    org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration
    org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
    org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration
    org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration$RestTemplateConfiguration
    org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
    org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration
    org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
    org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
    org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration
    org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration
    org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
    org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store
    org.springframework.context.annotation.internalAutowiredAnnotationProcessor
    org.springframework.context.annotation.internalCommonAnnotationProcessor
    org.springframework.context.annotation.internalConfigurationAnnotationProcessor
    org.springframework.context.annotation.internalRequiredAnnotationProcessor
    org.springframework.context.event.internalEventListenerFactory
    org.springframework.context.event.internalEventListenerProcessor
    preserveErrorControllerTargetClassPostProcessor
    propertySourcesPlaceholderConfigurer
    requestContextFilter
    requestMappingHandlerAdapter
    requestMappingHandlerMapping
    resourceHandlerMapping
    restTemplateBuilder
    serverProperties
    simpleControllerHandlerAdapter
    spring.http.encoding-org.springframework.boot.autoconfigure.web.HttpEncodingProperties
    spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties
    spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
    spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
    spring.mvc-org.springframework.boot.autoconfigure.web.WebMvcProperties
    spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
    standardJacksonObjectMapperBuilderCustomizer
    stringHttpMessageConverter
    tomcatEmbeddedServletContainerFactory
    viewControllerHandlerMapping
    viewResolver
    websocketContainerCustomizer
    welcomePageHandlerMapping
    2017-10-12 18:16:29.587  INFO 12580 --- [           main] c.top.test.controller.HelloApplication   : Started HelloApplication in 2.041 seconds (JVM running for 2.306)