Примечание: Я тестировал с Maven 4.0.0-rc-4. И я следил за https://maven.apache.org/maven-di.html, который говорит:
maven di-это структура инъекции зависимости Maven, которая вводится в Maven 4. Это успешно для Plectus iocd ioc. 330 /eclipse sisu (используется в Maven 3) в Maven. < /P>
< /blockquote>
Я принимаю это, чтобы означать, что мы больше не должны использовать ни один из: < /p>
[*]
Код: Выделить всё
@org.apache.maven.plugins.annotations.Component
[*]
Код: Выделить всё
@javax.inject.Inject< /code> / @jakarta.inject.inject < /code>. < /p>
< /li>
< /ol>
и теперь предполагается использовать: < /p>
[list]
@org.apache.maven.api.di.Inject
Но это не последовательно. Услуги могут быть введены во время тестирования, но не при использовании плагина в другом проекте. И наоборот, услуги можно получить с помощью Session :: getservice (класс) при использовании плагина в другом проекте, но не во время тестирования. />helloworldmojo.java
Код: Выделить всё
package com.example.ditests;
import org.apache.maven.api.Project;
import org.apache.maven.api.Session;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.services.ArtifactManager;
import org.apache.maven.api.services.DependencyResolver;
import org.apache.maven.api.services.OsService;
import org.apache.maven.api.services.ToolchainManager;
@Mojo(name = "hello-world")
public class HelloWorldMojo implements org.apache.maven.api.plugin.Mojo {
@Inject private Log log;
@Inject Session session;
@Inject Project project;
@Inject ArtifactManager artifacts;
@Inject DependencyResolver dependencies;
@Inject ToolchainManager toolchains;
@Inject OsService os;
@Override
public void execute() {
log.info("Hello, World!");
logService("session", session);
logService("project", project);
logService("artifacts", artifacts);
logService("dependencies", dependencies);
logService("toolchains", toolchains);
logService("os", os);
}
private void logService(String name, Object value) {
log.info(() -> "%s = %s".formatted(name, value));
}
}
Код: Выделить всё
package com.example.ditests;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.maven.api.plugin.testing.InjectMojo;
import org.apache.maven.api.plugin.testing.MojoTest;
import org.junit.jupiter.api.Test;
@MojoTest
class HelloWorldMojoTests {
@Test
@InjectMojo(goal = "hello-world")
void testInject(HelloWorldMojo mojo) {
assertDoesNotThrow(mojo::execute);
assertAll(
"Services not injected.",
() -> assertNotNull(mojo.session, "session"),
() -> assertNotNull(mojo.project, "project"),
() -> assertNotNull(mojo.artifacts, "artifacts"),
() -> assertNotNull(mojo.dependencies, "dependencies"),
() -> assertNotNull(mojo.toolchains, "toolchains"),
() -> assertNotNull(mojo.os, "os"));
}
}
Код: Выделить всё
4.1.0
com.example
ditests-maven-plugin
0.1.0-SNAPSHOT
maven-plugin
UTF-8
17
4.0.0-rc-4
5.13.3
7.0.0
org.apache.maven
maven-api-core
${mavenVersion}
provided
org.apache.maven
maven-api-di
${mavenVersion}
provided
org.junit.jupiter
junit-jupiter
${junitVersion}
test
org.apache.maven
maven-testing
${mavenVersion}
test
org.apache.maven
maven-core
${mavenVersion}
test
com.google.inject
guice
${guiceVersion}
test
org.apache.maven.plugins
maven-clean-plugin
3.5.0
org.apache.maven.plugins
maven-compiler-plugin
3.14.0
org.apache.maven.plugins
maven-resources-plugin
3.3.1
org.apache.maven.plugins
maven-jar-plugin
3.4.2
org.apache.maven.plugins
maven-surefire-plugin
3.5.3
org.apache.maven.plugins
maven-plugin-plugin
4.0.0-beta-1
org.apache.maven.plugins
maven-install-plugin
3.1.4
org.apache.maven.plugins
maven-enforcer-plugin
3.6.1
org.apache.maven.plugins
maven-enforcer-plugin
enforce
enforce
[4.0.0-rc-4,)
org.apache.maven.plugins
maven-surefire-plugin
-XX:+EnableDynamicAgentLoading
org.apache.maven.plugins
maven-plugin-plugin
java-annotations
< /code>
Проблема < /h1>
[b] Примечание: < /strong> Чтобы повторить, я протестировал с помощью Maven 4.0.0-rc-4. Но затем попытка использовать плагин в другом проекте сбои с ошибкой DI.
Однако, если я переключаю часть @Inject
Использование @Inject везде
POM и код не изменяются выше.
Код: Выделить всё
mvn clean install
< /code>
работает нормально. Тесты проходят и, как видно из журналов, услуги вводится: < /p>
[INFO] --- surefire:3.5.3:test (default-test) @ ditests-maven-plugin ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.ditests.HelloWorldMojoTests
[WARNING] [stderr] OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[WARNING] [stderr] [main] INFO anonymous - Hello, World!
[WARNING] [stderr] [main] INFO anonymous - session = Mock for InternalSession, hashCode: 1323676377
[WARNING] [stderr] [main] INFO anonymous - project = org.apache.maven.api.plugin.testing.stubs.ProjectStub@1bb15351
[WARNING] [stderr] [main] INFO anonymous - artifacts = Mock for ArtifactManager, hashCode: 2130400175
[WARNING] [stderr] [main] INFO anonymous - dependencies = org.apache.maven.impl.DefaultDependencyResolver@4fa822ad
[WARNING] [stderr] [main] INFO anonymous - toolchains = org.apache.maven.impl.DefaultToolchainManager@597f0937
[WARNING] [stderr] [main] INFO anonymous - os = org.apache.maven.impl.model.DefaultOsService@7ad1caa2
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.250 s -- in com.example.ditests.HelloWorldMojoTests
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
< /code>
Но если я попытаюсь использовать цель в другом проекте, он терпит неудачу. Эта команда: < /p>
mvn ditests:hello-world
< /code>
дает: < /p>
[ERROR] Failed to execute goal com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world (default-cli) on project test: Execution default-cli of goal com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world failed: Unable to lookup Mojo: Error while initializing binding BindingToConstructor[@Named("com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world") HelloWorldMojoFactory][]: No binding to construct an instance for key ArtifactManager. Existing bindings:
[ERROR] - @Named("com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world") HelloWorldMojo
[ERROR] - @Named("com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world") HelloWorldMojoFactory
[ERROR] - @Named("com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world") Mojo
[ERROR] - @Named("com.example:ditests-maven-plugin:0.1.0-SNAPSHOT:hello-world") Object
[ERROR] - HelloWorldMojo
[ERROR] - HelloWorldMojoFactory
[ERROR] - Log
[ERROR] - Mojo
[ERROR] - MojoExecution
[ERROR] - Object
[ERROR] - Project
[ERROR] - ProtoSession
[ERROR] - Session
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the '-e' switch
[ERROR] Re-run Maven using the '-X' switch to enable verbose output
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerExceptio
На основе ошибки в предыдущем разделе он выглядит как log , session и Project может быть введен просто нормально. Итак, я попытался переключить все остальное на сеанс :: getservice .
helloworldmojo.java [/b] (модифицирован)
Код: Выделить всё
package com.example.ditests;
import org.apache.maven.api.Project;
import org.apache.maven.api.Session;
import org.apache.maven.api.di.Inject;
import org.apache.maven.api.plugin.Log;
import org.apache.maven.api.plugin.annotations.Mojo;
import org.apache.maven.api.services.ArtifactManager;
import org.apache.maven.api.services.DependencyResolver;
import org.apache.maven.api.services.OsService;
import org.apache.maven.api.services.ToolchainManager;
@Mojo(name = "hello-world")
public class HelloWorldMojo implements org.apache.maven.api.plugin.Mojo {
@Inject private Log log;
@Inject Session session;
@Inject Project project;
ArtifactManager artifacts;
DependencyResolver dependencies;
ToolchainManager toolchains;
OsService os;
@Override
public void execute() {
artifacts = session.getService(ArtifactManager.class);
dependencies = session.getService(DependencyResolver.class);
toolchains = session.getService(ToolchainManager.class);
os = session.getService(OsService.class);
log.info("Hello, World!");
logService("session", session);
logService("project", project);
logService("artifacts", artifacts);
logService("dependencies", dependencies);
logService("toolchains", toolchains);
logService("os", os);
}
private void logService(String name, Object value) {
log.info(() -> "%s = %s".formatted(name, value));
}
}
< /code>
Теперь установка плагина сбой. Эта команда: < /p>
mvn clean install
< /code>
Не удастся во время тестирования: < /p>
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.ditests.HelloWorldMojoTests
[WARNING] [stderr] OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[WARNING] [stderr] [main] INFO anonymous - Hello, World!
[WARNING] [stderr] [main] INFO anonymous - session = Mock for InternalSession, hashCode: 1323676377
[WARNING] [stderr] [main] INFO anonymous - project = org.apache.maven.api.plugin.testing.stubs.ProjectStub@4d499d65
[WARNING] [stderr] [main] INFO anonymous - artifacts = Mock for ArtifactManager, hashCode: 2130400175
[WARNING] [stderr] [main] INFO anonymous - dependencies = null
[WARNING] [stderr] [main] INFO anonymous - toolchains = null
[WARNING] [stderr] [main] INFO anonymous - os = null
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 2.204 s expected: not
at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:49)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:35)
at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:312)
at com.example.ditests.HelloWorldMojoTests.lambda$testInject$3(HelloWorldMojoTests.java:23)
at org.junit.jupiter.api.AssertAll.lambda$assertAll$0(AssertAll.java:68)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:215)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:1024)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:570)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:560)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:265)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:727)
at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:77)
... 6 more
Suppressed: org.opentest4j.AssertionFailedError: toolchains ==> expected: not
at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:49)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:35)
at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:312)
at com.example.ditests.HelloWorldMojoTests.lambda$testInject$4(HelloWorldMojoTests.java:24)
at org.junit.jupiter.api.AssertAll.lambda$assertAll$0(AssertAll.java:68)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:215)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:1024)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:570)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:560)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:265)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:727)
at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:77)
... 6 more
Suppressed: org.opentest4j.AssertionFailedError: os ==> expected: not
at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:49)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:35)
at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:312)
at com.example.ditests.HelloWorldMojoTests.lambda$testInject$5(HelloWorldMojoTests.java:25)
at org.junit.jupiter.api.AssertAll.lambda$assertAll$0(AssertAll.java:68)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:215)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:1024)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:570)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:560)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:265)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:727)
at org.junit.jupiter.api.AssertAll.assertAll(AssertAll.java:77)
... 6 more
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR] HelloWorldMojoTests.testInject:18 Services not injected. (3 failures)
org.opentest4j.AssertionFailedError: dependencies ==> expected: not
org.opentest4j.AssertionFailedError: toolchains ==> expected: not
org.opentest4j.AssertionFailedError: os ==> expected: not
mvn clean install -DskipTests=true
< /code>
Затем выполнение: < /p>
mvn ditests:hello-world
< /code>
дает: < /p>
[INFO] --- ditests:0.1.0-SNAPSHOT:hello-world (default-cli) @ test ---
[INFO] Hello, World!
[INFO] session = org.apache.maven.internal.impl.DefaultSession@24839da
[INFO] project = org.apache.maven.internal.impl.DefaultProject@4897d181
[INFO] artifacts = org.apache.maven.internal.impl.DefaultArtifactManager@184e24cf
[INFO] dependencies = org.apache.maven.impl.DefaultDependencyResolver@84dd06
[INFO] toolchains = org.apache.maven.impl.DefaultToolchainManager@3b234151
[INFO] os = org.apache.maven.impl.model.DefaultOsService@36d3739f
< /code>
Все получается правильно. Как получить то же поведение во время тестирования, что и в «Производстве»?
Подробнее здесь: https://stackoverflow.com/questions/797 ... in-a-maven