Apache Commons Configuration2 的依赖声明为可选

dependency for Apache Commons Configuration2 declared as optional

我尝试简单地使用简单的 Apache Commons Configuration2 从属性文件加载配置。这是我的依赖项:

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-configuration2</artifactId>
        <version>2.1</version>
    </dependency>

我尝试启动我的网络应用程序并得到这个:

java.lang.ClassNotFoundException: org.apache.commons.beanutils.DynaBean
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.sun.proxy.$Proxy21.<clinit>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:739)
    at org.apache.commons.configuration2.builder.fluent.Parameters.createParametersProxy(Parameters.java:294)
    at org.apache.commons.configuration2.builder.fluent.Parameters.properties(Parameters.java:245)

可爱。什么时候不能用Maven自动获取依赖了?我查看 commons-configuration2 POM on Maven Central 并看到 commons-beanutil 被声明为 optional.

<dependency>
  <groupId>commons-beanutils</groupId>
  <artifactId>commons-beanutils</artifactId>
  <version>1.9.2</version>
  <optional>true</optional>
</dependency>

为什么明明需要它却声明为 "optional"?

这个依赖项被标记为可选的,因为它只是库的一些非核心功能所必需的,这意味着你仍然可以在没有安装这个依赖项的情况下使用库的大部分内容。

根据文档:Runtime dependencies for Commons Configuration 2.0

Commons Configuration 2.0 requires Java 6 or later.

A lot of dependencies are declared in the Maven POM. These are all needed during compile time. On runtime however you only need to add the dependencies to your classpath that are required by the parts of the Commons Configuration package you are using. The following table helps you to determine which dependencies you have to include based on the components you intend to use:

考虑到表格不容易包含在 SO 答案中,我将只列出 commons-configuration-2 中的功能,这需要您包含 beanutils:

  • 配置构建器
  • ConfigurationDynaBean

在您的情况下,根据您提供的堆栈跟踪,您正在使用配置生成器,因此需要在您的 pom 中手动包含 beanutils 依赖项。