人生苦短,我用Spring Boot

如果说Spring给Java开发带来的春天,那么Spring Boot就给Spring带来的春天.

Spring Boot , easy than easy

初探Spring Boot

使用Maven

  1. 父级依赖
1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
  1. 配置信息

    1
    2
    3
    4
    5
    6
    7
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
    </properties>
  2. 添加依赖

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  3. 添加编译插件

    1
    2
    3
    4
    5
    6
    7
    8
    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>

    Spirng Boot 核心

    1. @SpringBootApplication

      组合了@Configuration & @EnableAutoConfiguration & @ComponentScan 这三个注解,其中:

      • @EnableAutoConfiguration 让SpringBoot根据类路径中的jar包依赖为当前项目进行自动配置,例如添加了spring-boot-starter-web依赖,Spring Boot就会自动添加Tomcat和Spring MVC的依赖,那么Spring Boot会进行自动配置.
      • @ComponentScan 包扫描
      • @Configuration 标明这是个配置类
    2. @SpringBootApplication 有enclude属性,可以关闭特定的自动配置.

      1
      @SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

Spring Boot 的配置文件

有两种方式:application.properties和application.yml,推荐使用properties中

常规配置

application.properties中使用

1
2
book.author=canyuda
book.name=SpringBoot

属性中就可以使用@Value进行注入了

1
2
3
4
@Value("${book.author}")
private String bookAuthor;
@Value("${book.name}")
private String bookName;

自定义properties

对于自己的properties文件.使用@ConfigurationProperties(locations={"classpath:config/author.properties"}) ,使用如下注入:

1
2
3
4
@Value("${book.author}")
private String bookAuthor;
@Value("${book.name}")
private String bookName;

日志配置

Spring Boot 默认使用Logback作为日志框架

1
2
3
4
# 日志位置
logging.file=D:/myLog/log/log
# 日志级别
logging.level.org.springframework.web= DEBUG

环境切换

生产环,测试环境,开发环境之间的快速切换

application.properties中使用:

1
2
spring.profiles.active=dev
# spring.profiles.active=prod

分别可以选择application-dev.properties或者application-prod.properties中的配置,即application-{profile}.properties的配置.

Spring Boot 运行原理

Spring Boot 的Web开发