zoukankan      html  css  js  c++  java
  • Spring Boot使用Maven打包替换资源文件占位符

      在Spring Boot开发中,通过Maven构建项目依赖是一件比较舒心的事,可以为我们省去处理冲突等大部分问题,将更多的精力用于业务功能上。近期在项目中,由于项目集成了其他外部系统资源文件,需要根据不同的环境实现加载不同的JS资源文件,处理这个问题首先想到的便是通过判断当前环境实现动态加载JS,但是,在应用打包的时候已经明确了部署环境,对于静态资源的引用也是确定的,为何不在执行打包的过程中指定引用的资源路径?没错,尤其在通过Spring Boot的Maven打包时,可以通过简单的几行代码来实现实现。下面给出一个简单的例子,比如,在html页面我们需要动态的引入一个JS,JS的路径分别为http://www.cnblogs.com/funnyboy0128/test.js和http://www.cnblogs.com/funnyboy0128-test/test.js,假设分别对应到生产环境和开发环境,则处理如下:

    1、pom文件如下:

    <build>
      <plugins>
        <plugin>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
      </plugins>
      
         <!-- mavne打包动态修改替换占位符 -->
      <resources>  
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>  
        </resource>
      </resources>
    </build>

    <profiles>
      <profile>
        <id>dev</id>
        <properties>
          <funnyboy.env>http://www.cnblogs.com/funnyboy0128-test</funnyboy.env>
        </properties>
      </profile>

      <profile>
        <id>pro</id>
        <properties>
          <funnyboy.env>http://www.cnblogs.com/funnyboy0128</funnyboy.env>
        </properties>
      </profile>

    </profiles>

    2、资源 文件,例如xx.html中引用JS如下:

     <script type="text/javascript" src="@funnyboy.env@/test.js"></script>

    3、打完包测试一下:

    mvn package -Pdev后查看应用包的xx.html,内容如下:<script type="text/javascript" src="http://www.cnblogs.com/funnyboy0128-test/test.js"></script>

    mvn package -Ppro后查看应用包的xx.html,内容如下:<script type="text/javascript" src="http://www.cnblogs.com/funnyboy0128/test.js"></script>

    经过测试OK。

  • 相关阅读:
    Interesting Finds: 2008.03.19
    Interesting Finds: 2008.03.11
    Interesting Finds: 2008.03.27
    Interesting Finds: 2008.03.21
    每日日报
    每日日报
    每日日报
    每日日报
    idea怎么创建properties文件
    移动端rem.js
  • 原文地址:https://www.cnblogs.com/funnyboy0128/p/7693834.html
Copyright © 2011-2022 走看看