Roman Puchkovskiy Roman Puchkovskiy - 3 years ago 337
Java Question

Java 9: how to get access to javax.annotation.Resource at run time

I have a test:

public class ResourceTest {
public void test() throws ClassNotFoundException {

It tries to access
. In java 8 it worked, but in java 9 (I'm using Oracle JDK 9) it fails with
As explained here Spring: @Resource injection stopped working under JDK9 ,
from the JDK is not available by default in Java 9.

I'm trying to get access to it using module descriptor:

module test {
requires junit;

Here, I specifically request access to
module (which contains
). But the test still fails.

When I remove that
clause and add a dependency (as a library) which contains
, it works:


When I add them both (Maven dependency in
), compilation in IDEA fails with the following message:

the unnamed module reads package javax.annotation from both and java.annotation

But Maven build still succeeds!

If I add
module via command line, it works (with no Maven dependency and with

mvn clean test -DargLine="--add-modules"

Do I do something wrong with my module description? How can I get access to JDK-supplied
without command line switches?

The test project is available at

Answer Source

Just to clear out some confusion here. The ways to work stated in the question by you are alternatives and should not be combined as you have already seen.

the unnamed module reads package javax.annotation from both and java.annotation

So the way it would work is either:

You can use the compiler args to add modules



Make use of the being an upgradeable module which is when you can make use of the dependency


Ideally this would be a preferrable option to stick to as the former is just an alternate to use the @Deprecated module marked forRemoval.

So the required clause by itself it not enough to get access to a module... is this true for all JDK-supplied modules (excluding java.base), or it is only true for deprecated modules?

No, the requires is just a part of declaration. [Think about this, prior to JDK 9 if you used a statement import; in your class which was not added as a library(classpath) would that have worked?]. The module marked as required has to be on the modulepath for you to access it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download