2015-03-04 4 views
2

Я хочу переименовать статические файлы при создании файла WAR с помощью maven-war-plugin с номером версии. Для входа в инстансе, в моем проекте у меня есть файл:Переименование статических файлов при создании WAR-файла с использованием Maven

src/main/webapp/css/my.css 

Я хочу, чтобы она появилась в файле WAR, как:

css/my-versionNumber.css 

Тот же вопрос уже спросил (см Rename static files on maven war build), но приняли Ответ - переименование каталога. Я не хочу переименовывать каталог, я хочу переименовать фактический файл.

Возможно ли это?

ответ

2

ОК, я нашел способ, принципы происходят из: Automatic update of generated css files via m2e.

  1. Переименование файлов

    Я решил использовать Maven AntRun Plugin, потому что она позволяет переименовать несколько файлов, используя шаблон замены, см https://stackoverflow.com/a/16092997/1768736 для деталей.

    Альтернативные решения должны были использовать:

  2. Ма KE переименованы файлы, доступные для maven-war-plugin

    • Копирование файлов: идея состоит в том, чтобы скопировать переименованные файлы в временную директорию, которая будет добавлено maven-war-plugin в файл WAR в качестве веб-ресурса. maven-war-plugin строит WAR во время фазы packaging, поэтому перед этим нам нужно будет скопировать переименованные файлы.

    • Предотвращение maven-war-plugin для управления файлами, которые должны быть переименованы maven-antrun-plugin: это делается с использованием параметра warSourceExcludes.

  3. Сделать работу внутри Eclipse, с m2e-wtp

    • Изменение отображения жизненного цикла: проблема заключается в том, что m2e по умолчанию не выполняет все жизненные циклы, определенные в файле POM (чтобы увидеть жизненный цикл выполненный/проигнорированный, из Eclipse, перейдите к вашим свойствам проекта, затем Maven>Lifecycle Mapping).Поэтому вам нужно использовать поддельный плагин org.eclipse.m2e.lifecycle-mapping, чтобы добавить жизненный цикл maven-antrun-plugin, см. life cycle mapping documentation.

    • Изменения maven-antrun-plugin вывод каталог: проблема заключается в том, что m2e-wtp приобретает свои веб-ресурсы, прежде чем любой жизненный цикл может быть запущен, поэтому, перед тем maven-antrun-plugin может переименовать файлы. В качестве обходного пути мы создаем профиль, который активируется только тогда, когда проект строится на m2e, чтобы изменить свойство, используемое для установки выходного каталога maven-antrun-plugin, чтобы напрямую писать в m2e-wtp веб-ресурсы.

Вот так! POM snippet:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
      http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    ... 

    <properties> 
    <!-- properties used to rename css files with version number. --> 
    <css.version>${project.version}</css.version> 
    <!-- Temp directory where to copy renamed files, later added by maven-war-plugin as web-resources. --> 
    <rename.tmp.directory>${project.build.directory}/rename_tmp</rename.tmp.directory> 
    </properties> 

    <!-- There is a problem when running the webapp from Eclipse: m2e-wtp acquires 
    the web-resources before any lifecycle can be launched, so, before 
    maven-antrun-plugin can rename the files. We define a profile so that 
    maven-antrun-plugin copies files directly into the m2e-wtp web-resources directory, 
    when running from Eclipse. --> 
    <profiles> 
    <profile> 
     <id>m2e</id> 
     <!-- This profile is only active when the property "m2e.version" 
     is set, which is the case when building in Eclipse with m2e, 
     see https://stackoverflow.com/a/21574285/1768736. --> 
     <activation> 
     <property> 
      <name>m2e.version</name> 
     </property> 
     </activation> 
     <properties> 
     <rename.tmp.directory>${project.build.directory}/m2e-wtp/web-resources/</rename.tmp.directory> 
     </properties> 
    </profile> 
    </profiles> 

    ... 

    <build> 
    <plugins> 
     <plugin> 
     <artifactId>maven-antrun-plugin</artifactId> 
     <executions> 
      <execution> 
      <goals> 
       <goal>run</goal> 
      </goals> 
      <id>rename-resources</id> 
      <!-- perform copy before the package phase, 
      when maven-war-plugin builds the WAR file --> 
      <phase>process-resources</phase> 
      <configuration> 
       <target> 
       <!-- copy renamed files. --> 
       <copy todir="${rename.tmp.directory}/css/"> 
        <fileset dir="src/main/webapp/css/"> 
        <include name="**/*.css" /> 
        </fileset> 
        <!-- See other Mappers available at http://ant.apache.org/manual/Types/mapper.html --> 
        <mapper type="glob" from="*.css" to="*-${css.version}.css"/> 
       </copy> 
       </target> 
      </configuration> 
      </execution> 
     </executions> 
     </plugin> 

     <plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-war-plugin</artifactId> 
     <configuration> 
      <!-- We do no let the maven-war-plugin take care of files that will be renamed. 
      Paths defined relative to warSourceDirectory (default is ${basedir}/src/main/webapp) --> 
      <warSourceExcludes>css/</warSourceExcludes> 
      <webResources> 
      <!-- include the resources renamed by maven-antrun-plugin, 
      at the root of the WAR file --> 
      <resource> 
       <directory>${rename.tmp.directory}</directory> 
       <includes> 
       <include>**/*</include> 
       </includes> 
      </resource> 
      </webResources> 
     </configuration> 
     </plugin> 

     ... 
    </plugins> 


    <!-- When running server from Eclipse, we need to tell m2e to execute 
    maven-antrun-plugin to rename files, by default it doesn't. We need to modify the life cycle mapping. --> 
    <pluginManagement> 
     <plugins> 
     <!-- This plugin is not a real one, it is only used by m2e to obtain 
     config information. This is why it needs to be put in the section 
     pluginManagement, otherwise Maven would try to download it. --> 
     <plugin> 
      <groupId>org.eclipse.m2e</groupId> 
      <artifactId>lifecycle-mapping</artifactId> 
      <version>1.0.0</version> 
      <configuration> 
      <lifecycleMappingMetadata> 
       <pluginExecutions> 
       <pluginExecution> 
        <pluginExecutionFilter> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-antrun-plugin</artifactId> 
        <versionRange>[1.0.0,)</versionRange> 
        <goals> 
         <goal>run</goal> 
        </goals> 
        </pluginExecutionFilter> 
        <action> 
        <execute> 
         <!-- set to true, otherwise changes are not seen, 
         e.g., to a css file, and you would need to perform 
         a project update each time. --> 
         <runOnIncremental>true</runOnIncremental> 
        </execute > 
        </action> 
       </pluginExecution> 
       </pluginExecutions> 
      </lifecycleMappingMetadata> 
      </configuration> 
     </plugin> 
     </plugins> 
    </pluginManagement> 

    ... 

    </build> 

    ... 
</project> 
-1

Вам нужно определить

<properties> 
    <css.version>1.1.0</css.version> 
</properties> 

После этого называют ее EL CSS/$ {} css.version .css

+0

Это не работает, свойство не заменяется в имени файла. И насколько я знаю, фильтрация работает для содержимого файла, а не для имени файла, не так ли? – FBB

+0

я использую, чтобы использовать его, чтобы установить версию для библиотеки, такие как: ... Это некоторый текст 3,3. 0.ga ... <зависимостями> org.hibernate зимуют $ {hibernate.version} ...

+0

Таким образом, вы используете это для переименования библиотеки. Я хочу переименовать статический файл (если бы я хотел просто переименовать библиотеку, я мог бы использовать параметр 'outputFileNameMapping' из maven-war-plugin). – FBB

Смежные вопросы