Spring Boot Linux 部署 一

最近公司做一个小程序使用Spring Boot 管理,我用了最新的版本2.0.3.RELEASE,期间碰到了很多坑,记录一下部署的过程。

 

Spring Boot 提供了一个插件spring-boot-maven-plugin 这个插件用过Spring Boot的人应该都知道,创建项目的时候构建工具就会把这个插件添加进去。

重点是configuration中的<executable>true</executable>配置添加这个配置之后 package打成的包就是可执行的jar,就是spring-boot-maven-plugin将执行脚本与程序一起打成了jar,可以用文本编辑器打开jar包就能看见。

 jar包打完之后在linux中./xxx.jar就可以直接运行,但是运行效果不是我们想要的那样,正常的linux中运行某些系统都是server start这样的形势,然后启动完之后也会显示xxx启动成功 ./xxx.jar

<plugin>
 <artifactId>maven-assembly-plugin</artifactId>
</plugin>

 

一、jar运行

1、在pom文件中添加如下插件配置,configuration中的<executable>true</executable>配置是要求插件打可执行jar包。

<plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 <configuration>
  <executable>true</executable>
 </configuration>
</plugin>

2、执行maven clean 然后package,jar包就生成了,而且是可执行的,因为插件将执行脚本也放到了jar包里。

二、外部配置文件

1、引用外部配置文件

基本每一个应用都有配置文件,Spring Boot 也会默认在项目根目录加载application.properties这对程序员是非常友好的,以前一些特别格式化的配置全部都省略了,比如server.port=9090 一行就能指定应用使用的端口号。

Spring Boot 官方文档是这么说的

24.3 Application property files
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

这里说了四种方式可以把配置文件放到外部的。
第一种是在jar包的同一目录下建一个config文件夹,然后把配置文件放到这个文件夹下;
第二种是直接把配置文件放到jar包的同级目录;
第三种在classpath下建一个config文件夹,然后把配置文件放进去;
第四种是在classpath下直接放配置文件。

那么Spring Boot 插件打完的jar包application.properties在jar包里,很不方便修改也会破坏jar包结构,所以使用spring-boot-maven-plugin生成的可执行jar会默认加载config/application.properties,这样就很方便修改了。
2、优先级别

上面表述的四种方式的  优先级是从一到四一次降低的。

3、不同环境的配置文件引用

Spring Boot 默认加载配置文件的规则是application*.properties 所以可以有多个application*.properties作为在不同环境中使用,

application.properties
application-dev.properties

。。。

只需要在application.properties中指定Spring.profiles.actice=dev来指定加载application-dev.properties,当然也可以是多个,只需要都好分割就好啦;

也可以在执行时指定 java -jar myproject.jar --spring.profiles.active = dev

如果嫌application.properties太长了也可以通过spring.config.name=app来修改配置名