快速搭建SpringBoot项目

629 阅读4分钟

SpringBoot介绍

随着动态语言的流行(Ruby,Groovy,Scala,Node.js),Java的开发显得格外的笨重:繁多的配置,低下的开发效率,复杂的部署流程以及第三方技术集成难度大。 在上述环境下,SpringBoot应运而生。它使用“习惯由于配置”的理念让项目快速运行起来。使用SpringBoot很容易创建一个独立运行(运行jar,内嵌Servlet容器)准生产级别的基于Spring框架的项目,使用SpringBoot可以不用或只需要很少的Spring配置。

SpringBoot核心特点

  • 可以以jar包的形式独立运行,运行一个SpringBoot项目只需通过 java -jar xx.jar来运行
  • 内嵌Servlet容器,SpringBoot可以选择Tomcat,Jetty或者Undertow,这样我们无须以war包形式部署项目
  • 简化Maven配置,SpringBoot提供了一系列的starter pom 来简化Maven的依赖加载
  • SpringBoot会根据在类路径中的jar包,类,为jar包中的类自动配置Bean,这样就极大的减少了我们要使用的配置
  • SpringBoot提供了基于http,ssh,telnet对运行时的项目进行监控
  • 不借助于代码生成来实现,而是通过条件注解来实现,这也是Spring4.x的新特性,不需要任何的xml配置即可实现Spring的所有配置

搭建第一个SpringBoot入门程序

  • 创建一个maven的jar项目工程。

  • 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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.zichen</groupId>
      <artifactId>springboot</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>1.5.6.RELEASE</version>
      </parent>
    
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      </dependencies>
    
      <!-- 改变JDK版本 -->
      <build>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
    
                  <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                  </configuration>
              </plugin>
          </plugins>
      </build>
    </project>
    
  • 启动类FirstApplication的写法

    /**
     * 启动类
     * @author Administrator
     *
     */
    @SpringBootApplication
    public class FirstApplication {
        public static void main(String[] args) {
            SpringApplication.run(FirstApplication.class, args);
        }
    }
    
  • 运行测试成功

@EnableAutoConfiguration启用自动配置

@EnableAutoConfiguration该注解会使SpringBoot根据项目依赖的jar包自动配置项目的配置项。例如:我们添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,Spring Boot就会自动配置Tomcat和SpringMVC。

Spring Boot支持的自动配置如下:

关闭自动配置

@EnableAutoConfiguration(exclude={RedisAutoConfiguration.class})

自定义banner

  • 打开网站:自定义banner网站地址

  • 拷贝生成的字符到一个文本文件中,并且将该文件命名为banner.txt。将banner.txt拷贝到项目的resources目录中

  • 将banner.txt拷贝到项目的resources目录中

    banner.txt

    ////////////////////////////////////////////////////////////////////
    //                          _ooOoo_                               //
    //                         o8888888o                              //
    //                         88" . "88                              //
    //                         (| ^_^ |)                              //
    //                         O\  =  /O                              //
    //                      ____/`---'\____                           //
    //                    .'  \\|     |//  `.                         //
    //                   /  \\|||  :  |||//  \                        //
    //                  /  _||||| -:- |||||-  \                       //
    //                  |   | \\\  -  /// |   |                       //
    //                  | \_|  ''\---/''  |   |                       //
    //                  \  .-\__  `-`  ___/-. /                       //
    //                ___`. .'  /--.--\  `. . ___                     //
    //              ."" '<  `.___\_<|>_/___.'  >'"".                  //
    //            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
    //            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
    //      ========`-.____`-.___\_____/___.-`____.-'========         //
    //                           `=---='                              //
    //      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
    //            佛祖保佑       永不宕机     永无BUG                   //
    ////////////////////////////////////////////////////////////////////
    
  • 启动项目

全局配置文件

Spring Boot项目使用一个全局的配置文件application.properties或者是application.yml,在resources目录下或者类路径下的/config下,一般我们放到resources下。

  • 修改tomcat的端口为8989

    server.port=8989
    
  • 进入DispatcherServlet的规则为:*.html

    server.context-path=/hello
    

  • 查询全配置

    # BANNER
    banner.charset=UTF-8 # Banner file encoding.
    banner.location=classpath:banner.txt # Banner file location.
    banner.image.location=classpath:banner.gif # Banner image file location (jpg/png can also be used).
    banner.image.width= # Width of the banner image in chars (default 76)
    banner.image.height= # Height of the banner image in chars (default based on image height)
    banner.image.margin= # Left hand image margin in chars (default 2)
    banner.image.invert= # If images should be inverted for dark terminal themes (default false)
    
    # LOGGING
    logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
    logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
    logging.file= # Log file name. For instance `myapp.log`
    logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
    logging.path= # Location of the log file. For instance `/var/log`
    logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
    logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
    logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
    logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
    

starter pom列表

SpringBoot为我们提供了企业级开发绝大多数场景的starter pom,只要使用了应用场景所需的starter pom,相关的技术配置将会消除,就可以得到Spring Boot为我们提供的自动配置的Bean。

读取自定义配置

  • 在application.properties文件中自定义属性:例如 book.author=张三 book.name=SpringBoot

  • 使用@Value(“${book.author}”) 获取自定义属性的值

    # 紫晨
    book.author=紫晨
    book.name=SpringBoot
    

类型安全的配置

使用@Value注入每个自定义配置在项目中显得很麻烦,当自定义属性很多时需要注入很多次 SpringBoot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties中的属性和一个Bean的属性关联,从而实现类型安全的配置

  • 在application.properties文件中自定义属性:

    例如

        book.author=张三
        book.name=SpringBoot
        
    
  • @ConfigurationProperties(prefix="book")

Profile配置

Profile是针对不同的环境对不同的配置提供支持的,全局Profile配置使用application-*.properties

  • application-prod.properties 生产模式的配置

  • application-sit.properties 线上模式的配置

  • application-dev.properties 开发模式的配置

通过在application.properties中设置spring.profiles.active=dev来指定活动的Profile.

spring.profiles.active=dev

SpringBoot自动配置的原理