Springboot资源热加载



起因

在做一个内容销售系统的时候,遇到一个问题:

在将商品摆上货架时,如果使用的图片是通过文件上传的形式发送到后端,后端将其保存到resources目录中,在使用服务端本地的资源显示该图片时,会出现加载不出来的情况,只有当服务器重新启动,才能看到这些图片。

在自己实验、Google、百度了一通之后,得出一个结论,就是Spring默认会在应用启动时加载resources中的资源,一旦应用启动,之后放入resources中的资源将不会被加载。

解决方案

在pom.xml中加入一个插件,如下:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.5.6.RELEASE</version>
    <configuration>
        <!-- 下面这一行即为自动加载resources的配资-->
        <addResources>true</addResources>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

接下来要在命令行中输入mvn spring-boot:run来启动应用,否则依然无法自动加载resources文件

Spring boot maven plugin

甩出Spring Boot Maven Plugin的官方网站

这是一款Spring开发的用于在maven中提供Spring boot支持的插件

  • spring-boot:run 运行spring-boot应用
  • spring-boot:repackage 重新打包可执行的jar/war包
  • spring-boot:start/stop 一般用来执行测试(集成)
  • spring-boot:build-info 生成构建信息

如果需要额外的配置需求,请直接查询官网

遇到的问题

由于我的项目是分module构建的,在使用spring-boot maven plugin时,出现一个error:

Unable to find a suitable main class, please add a 'mainClass' property 

Google之后发现,spring-boot maven plugin要求有启动的main Class,可以在pom.xml文件中配置:

  1. 如果pom.xml是继承自spring-boot-starter-parent,可以在properties元素中加入<main-class>xxx</main-class>
  2. 如果pom.xml不是继承自spring-boot-starter-parent,那么可以在插件的属性中加入属性来指定
  3. 当然,即使不设定mainClass属性,插件也会自动搜索项目中包含有public void main(String[] args)的类来作为启动类

那么照理来说,spring-boot插件应该会自动找到我的启动类来启动,anyway,我又主动配置了一下属性,没想到这回又出现了这个错误:

Unable to find a suitable main class, please add a 'mainClass' property

然后又开始Google、Google、Google……

最终找到了解决方法:

首先将父pom.xml中的spring-boot plugin配置为:

<build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
</build>

然后在包含有主启动类的module pom.xml中,加入:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
      <fork>true</fork>
      <skip>false</skip>
      <addResources>true</addResources>
    </configuration>
    <executions>
      <execution>
        <goals>
          <goal>repackage</goal>
        </goals>
      </execution>
    </executions>
</plugin>

这时候再使用mvn spring-boot:run就可以启动应用了


-------------本文结束感谢您的阅读-------------
0%