Spring: @Resource injection stopped working under JDK9

前端 未结 2 1460
忘了有多久
忘了有多久 2020-12-09 20:21

In my @Configuration class I have dependendies like the following:

@Configuration
public class MyConfig {
    @Resource(name = \"firstDataSource         


        
相关标签:
2条回答
  • 2020-12-09 20:48

    Adding a few missing details.

    Spring @Resource-driven injection only works when javax.annotation.Resource is available at run time. Spring makes a check:

    private static final boolean jsr250Present =
            ClassUtils.isPresent("javax.annotation.Resource", AnnotationConfigUtils.class.getClassLoader());
    

    and then uses that jsr250Present variable to see whether @Resource-based injection (and also @PostConstruct/@PreDestroy functionality) should be enabled.

    In my case, under JDK 9, this class was not available in run time because it belongs to a separate module java.ws.xml.annotation (separate from the basic java.base module containing java.lang and some other packages that is always available). To solve the problem, one of the following approaches may be taken:

    1. Add javax.annotation-api library to my application classpath, as @AlanBateman and @nullpointer suggested.
    2. As an alternative, java may be instructed to add the module using a command line switch: --add-modules java.xml.ws.annotation. This leaves the code intact.
    0 讨论(0)
  • 2020-12-09 20:50

    The java.xml.ws.annotation being deprecated in jdk9 is possibly the cause of what you're facing. Since the annotation @Resource is from the package javax.annotation exported by the same module.

    You might want to provide javatm-common-annotations as an upgradeable module for java.xml.ws.annotation which exports the javax.annotation.

    This standalone release of Java(TM) Common Annotations uses a Java Platform Module System "automatic" module name of java.annotation, to match the module name used in JDK 9.

    The search on central suggests, you can use:-

    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.3.1</version>
    </dependency>
    

    This runs fine on my machine with your shared code.


    Also, a note about the code that you've shared. Since you're migrating to using JDK9, you should migrate to using latest springframework dependencies released as on 28-9-2017:-

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.0.RELEASE</version>
    </dependency>
    

    Edit : Do take a look at Roman's answer for an alternate to make use of --add-modules in case you are not planning to migrate to the javaee explosed module yet.

    0 讨论(0)
提交回复
热议问题