问题描述
maven有时有点超过我的头...我创建了一个对SLF4J和log4j具有可选依赖性的库.通过可选,我的意思是:
- 我的图书馆需要在编译时间的那些记录框架
- 我的库在运行时不需要它们,但是如果它"发现"它们,它将使用它们
目前,我将这种依赖性标记为"可选"和"提供":
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <type>jar</type> <scope>provided</scope> <optional>true</optional> </dependency>
但是我的一些用户报告了问题,因为他们不需要log4/slf4j.我的依赖性正确吗?不幸的是,我发现官方文档太抽象了,无法理解这个问题.
推荐答案
您是否检查过/a>文档.它很好地描述了您的用例.将依赖项标记为可选的,不会将它们作为使用库的应用程序依赖性解析(即使范围为compile).
在<scope>provided</scope>的差异中,用于运行时环境将提供的所需依赖关系<optional>true</optional>依赖性不一定是必需对于项目中的某些功能,如果不使用该功能,则不需要.).
如果使用您的库的项目将使用可选依赖项提供的任何功能范围,则该项目必须自行声明这些依赖项.
由于您的配置对我来说似乎是正确的,因此我不知道发生了什么原因.也许您的可选依赖项可以由其他库在您不期望的版本中解决.当然,这可能会引起问题.
问题描述
Maven is a bit over my head sometimes... I have created a library which has an optional dependency on slf4j and on log4j. By optional, I mean:
- My library needs those logging frameworks at compile time
- My library doesn't need them at runtime, but if it "discovers" them, it will use them
Currently, I have marked that dependency as "optional" and "provided":
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <type>jar</type> <scope>provided</scope> <optional>true</optional> </dependency>
But some of my users have reported issues, because they don't need log4 / slf4j. Is my dependency correct? Unfortunately, I find the official documentation a bit too abstract to understand this problem.
推荐答案
Did you check this documentation. It describes your use case very good. Marking dependencies as optional will not resolve them as transitive dependencies in the application which use your library (even if the scope is compile).
In difference to <scope>provided</scope> which is used for required dependencies which will be provided by the runtime environment an <optional>true</optional> dependency is not necessarily meant to be required (The idea is that some of the dependencies are only used for certain features in the project, and will not be needed if that feature isn't used.).
If a project which uses your library will use any functionallity provided by the optional dependencies the project has to declare these dependencies for their own.
As your configuration seems to be correct for me I do not know the reason what probles occur. Maybe your optional dependencies get resolved by other libraries in versions you do not expect. That of course might cause problems.