是否可以使用 maven build 在 war 文件中只包含使用过的类? [英] Is it possible to include only the used classes in a war file with maven build?

查看:62
本文介绍了是否可以使用 maven build 在 war 文件中只包含使用过的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的 pom.xml 文件中有这个依赖项:

Say I have this dependency in my pom.xml file:

  <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>6.0</version>
  </dependency>

当我做一个

clean install

所有的 javaee-api-6.0.jar 都会包含在 WEB-INF\lib 文件夹下的 war 文件中.

all the javaee-api-6.0.jar will be included in the war file under WEB-INF\lib folder.

是否有可能不包含整个 jar,而只包含我使用的类及其依赖项?

Is it possible that instead of including the whole jar, only classes that I use and their dependencies are included?

推荐答案

如果您要部署到 Java EE 应用服务器中,那么整个 JAR 已经由应用服务器提供,并且可以从 WAR 文件中省略.您可以通过将其放入提供的范围来完成此操作:

If you're deploying into a Java EE application server, that entire JAR is already provided by the application server, and can be omitted from the WAR file. You can accomplish this by putting it into the provided scope:

  <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>6.0</version>
      <scope>provided</scope>
  </dependency>

这使得该依赖项可用于编译和测试执行,但不会将其打包到 WAR 中.

That makes that dependency available for compilation and test execution, but will not package it into the WAR.

相比之下,试图确定您需要哪些单独的类,以便您只能包含它们的类文件,这最终是毫无意义的努力.JVM 仅在使用时加载类 - 即不加载未使用的类.

In contrast, trying to determine which individual classes you need so you can only include their class files is an ultimately pointless endeveor. The JVM only loads classes when they are used - that is, unused classes are not loaded.

由于反射,通常无法在编译时识别使用的类.例如,考虑:

It is generally impossible to identify the used classes at compile time due to reflection. For instance, consider:

System.console().printf("Please specify the implementation class to use");
String className = System.console().readLine();
FooService service = (FooService) Class.forName(className).newInstance();
service.work();

您可以让 JVM 记录加载了哪些类,但是不同的执行可以使用不同的类...

You can get the JVM to log which classes are loaded, but different executions can use different classes ...

这篇关于是否可以使用 maven build 在 war 文件中只包含使用过的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆