Spring Boot 入门搭建

一、前言

Spring Boot 的设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

二、环境搭建

创建一个 maven 工程,目录结构如下图:

2.1 添加依赖

创建 maven 工程,在 pom.xml 文件中添加如下依赖:

 1 <!-- 定义公共资源版本 -->
 2 <parent>
 3     <groupId>org.springframework.boot</groupId>
 4     <artifactId>spring-boot-starter-parent</artifactId>
 5     <version>1.5.6.RELEASE</version>
 6     <relativePath /> 
 7 </parent>
 8 
 9 <properties>
10     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
11     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
12     <java.version>1.8</java.version>
13 </properties>
14 
15 <dependencies>
16     <!-- 上边引入 parent,因此 下边无需指定版本 -->
17     <!-- 包含 mvc,aop 等jar资源 -->
18     <dependency>
19         <groupId>org.springframework.boot</groupId>
20         <artifactId>spring-boot-starter-web</artifactId>
21     </dependency>
22 </dependencies>
23 
24 <build>
25     <plugins>
26         <plugin>
27             <groupId>org.springframework.boot</groupId>
28             <artifactId>spring-boot-maven-plugin</artifactId>
29         </plugin>
30     </plugins>
31 </build>

2.2 创建目录和配置文件

创建 src/main/resources 源文件目录,并在该目录下创建 application.properties 文件、static 和 templates 的文件夹。

application.properties:用于配置项目运行所需的配置数据。

static:用于存放静态资源,如:css、js、图片等。

templates:用于存放模板文件。

目录结构如下:

2.3 创建启动类

在 com.boot.springboot 包下创建启动类,如下:

 1 /**
 2  该注解指定项目为springboot,由此类当作程序入口
 3  自动装配 web 依赖的环境
 4 
 5 **/
 6 @SpringBootApplication
 7 public class SpringbootApplication {
 8 
 9     public static void main(String[] args) {
10         SpringApplication.run(SpringbootApplication.class, args);
11     }
12 }

2.4 案例演示

创建 com.boot.springboot.controller 包,在该包下创建一个 Controller 类,如下:

1 @RestController
2 public class TestController {
3 
4     @GetMapping("/helloSpringBoot")
5     public String helloSpringBoot() {
6         return "hello spring boot";
7     }
8 }

在 SpringbootApplication 文件中运行启动类,出现如下图所示则说明启动成功

打开浏览器访问 http://localhost:8080/helloSpringBoot,结果如下:

三、热部署

当我们修改文件和创建文件时,都需要重新启动项目。这样频繁的操作很浪费时间,配置热部署可以让项目自动加载变化的文件,省去的手动操作。

在 pom.xml 文件中添加如下配置:

 1 <!-- 热部署 -->
 2 <dependency>
 3     <groupId>org.springframework.boot</groupId>
 4     <artifactId>spring-boot-devtools</artifactId>
 5     <optional>true</optional>
 6     <scope>true</scope>
 7 </dependency>
 8 
 9 <build>
10     <plugins>
11         <plugin>
12             <groupId>org.springframework.boot</groupId>
13             <artifactId>spring-boot-maven-plugin</artifactId>
14             <configuration>
15                 <!-- 没有该配置,devtools 不生效 -->
16                 <fork>true</fork>
17             </configuration>
18         </plugin>
19     </plugins>
20 </build>

配置好 pom.xml 文件后,我们启动项目,随便创建/修改一个文件并保存,会发现控制台打印 springboot 重新加载文件的信息。如下图:

  

四、多环境切换

application.properties 是 springboot 在运行中所需要的配置信息。

当我们在开发阶段,使用自己的机器开发,测试的时候需要用的测试服务器测试,上线时使用正式环境的服务器。

这三种环境需要的配置信息都不一样,当我们切换环境运行项目时,需要手动的修改多出配置信息,非常容易出错。

为了解决上述问题,springboot 提供多环境配置的机制,让开发者非常容易的根据需求而切换不同的配置环境。

在 src/main/resources 目录下创建三个配置文件:

  application-dev.properties:用于开发环境

  application-test.properties:用于测试环境

  application-prod.properties:用于生产环境

我们可以在这个三个配置文件中设置不同的信息,application.properties 配置公共的信息。

在 application.properties 中配置:

  spring.profiles.active=dev

表示激活 application-dev.properties 文件配置, springboot 会加载使用 application.properties 和 application-dev.properties 配置文件的信息。

同理,可将 spring.profiles.active 的值修改成 test 或 prod 达到切换环境的目的。如下图:

更换运行环境:

五、配置日志

5.1 配置 logback(官方推荐使用)

5.1.1 配置日志文件

spring boot 默认会加载 classpath:logback-spring.xml 或者 classpath:logback-spring.groovy。

如需要自定义文件名称,在 application.properties 中配置 logging.config 选项即可。

在 src/main/resources 下创建 logback-spring.xml 文件,内容如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <configuration>
 3     <!-- 文件输出格式 -->
 4     <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
 5     <!-- test文件路径 -->
 6     <property name="TEST_FILE_PATH" value="d:/test.log" />
 7     <!-- pro文件路径 -->
 8     <property name="PRO_FILE_PATH" value="/opt/test/log" />
 9 
10     <!-- 开发环境 -->
11     <springProfile name="dev">
12         <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
13             <encoder>
14                 <pattern>${PATTERN}</pattern>
15             </encoder>
16         </appender>
17         <logger name="com.light.springboot" level="debug" />
18         <root level="info">
19             <appender-ref ref="CONSOLE" />
20         </root>
21     </springProfile>
22 
23     <!-- 测试环境 -->
24     <springProfile name="test">
25         <!-- 每天产生一个文件 -->
26         <appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
27             <!-- 文件路径 -->
28             <file>${TEST_FILE_PATH}</file>
29             <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
30                 <!-- 文件名称 -->
31                 <fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
32                 <!-- 文件最大保存历史数量 -->
33                 <MaxHistory>100</MaxHistory>
34             </rollingPolicy>
35             <layout class="ch.qos.logback.classic.PatternLayout">
36                 <pattern>${PATTERN}</pattern>
37             </layout>
38         </appender>
39         <root level="info">
40             <appender-ref ref="TEST-FILE" />
41         </root>
42     </springProfile>
43 
44     <!-- 生产环境 -->
45     <springProfile name="prod">
46         <appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
47             <file>${PRO_FILE_PATH}</file>
48             <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
49                 <fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
50                 <MaxHistory>100</MaxHistory>
51             </rollingPolicy>
52             <layout class="ch.qos.logback.classic.PatternLayout">
53                 <pattern>${PATTERN}</pattern>
54             </layout>
55         </appender>
56         <root level="warn">
57             <appender-ref ref="PROD_FILE" />
58         </root>
59     </springProfile>
60 </configuration>

其中,springProfile 标签的 name 属性对应 application.properties 中的 spring.profiles.active 的配置。

即 spring.profiles.active 的值可以看作是日志配置文件中对应的 springProfile 是否生效的开关。

5.2 配置 log4j2

5.2.1 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

5.2.2 配置日志文件

spring boot 默认会加载 classpath:log4j2.xml 或者 classpath:log4j2-spring.xml。

如需要自定义文件名称,在 application.properties 中配置 logging.config 选项即可。

log4j2.xml 文件内容如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3     <properties>
 4         <!-- 文件输出格式 -->
 5         <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
 6     </properties>
 7     <appenders>
 8         <Console name="CONSOLE" target="system_out">
 9             <PatternLayout pattern="${PATTERN}" />
10         </Console>
11     </appenders>
12     <loggers>
13         <logger name="com.light.springboot" level="debug" />
14         <root level="info">
15             <appenderref ref="CONSOLE" />
16         </root>
17     </loggers>
18 </configuration>

log4j2 不能像 logback 那样在一个文件中设置多个环境的配置数据,只能命名 3 个不同名的日志文件,分别在 application-dev,application-test 和 application-prod 中配置 logging.config 选项。

除了在日志配置文件中设置参数之外,还可以在 application-*.properties 中设置,日志相关的配置:

1 logging.config                    # 日志配置文件路径,如 classpath:logback-spring.xml
2 logging.exception-conversion-word # 记录异常时使用的转换词
3 logging.file                      # 记录日志的文件名称,如:test.log
4 logging.level.*                   # 日志映射,如:logging.level.root=WARN,logging.level.org.springframework.web=DEBUG
5 logging.path                      # 记录日志的文件路径,如:d:/
6 logging.pattern.console           # 向控制台输出的日志格式,只支持默认的 logback 设置。
7 logging.pattern.file              # 向记录日志文件输出的日志格式,只支持默认的 logback 设置。
8 logging.pattern.level             # 用于呈现日志级别的格式,只支持默认的 logback 设置。
9 logging.register-shutdown-hook    # 初始化时为日志系统注册一个关闭钩子

六、打包运行

打包的形式有两种:jar 和 war。

6.1 打包成可执行的 jar 包

默认情况下,通过 maven 执行 package 命令后,会生成 jar 包,且该 jar 包会内置了 tomcat 容器,因此我们可以通过 java -jar 就可以运行项目,如下图:

6.2 打包成部署的 war 包

让 SpringbootApplication 类继承 SpringBootServletInitializer 并重写 configure 方法,如下:

 1 @SpringBootApplication
 2 public class SpringbootApplication extends SpringBootServletInitializer {
 3 
 4     @Override
 5     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
 6         return application.sources(SpringbootApplication.class);
 7     }
 8 
 9     public static void main(String[] args) {
10         SpringApplication.run(SpringbootApplication.class, args);
11     }
12 }

修改 pom.xml 文件,将 jar 改成 war,如下:

 1 <packaging>war</packaging> 

打包成功后,将 war 包部署到 tomcat 容器中运行即可。

七、参考资料

猜你喜欢

转载自www.cnblogs.com/liuqing576598117/p/9593002.html
今日推荐