在我的 @Configuration
类中,我有如下依赖项:
@Configuration
public class MyConfig {
@Resource(name = "firstDataSource")
private DataSource firstDataSource;
// more code
}
依赖注入(inject)在 Oracle JDK 8 中有效:firstDataSource
字段已成功注入(inject)非空值。
现在我尝试在 JDK 9 中运行该应用程序(没有修改)。结果是 @Resource
不再触发依赖注入(inject):使用此注释注释的所有内容都保持为 null
.
@Resource
停止工作的原因可能是什么?
项目中使用了Spring 4.0.9
这是一个演示问题的测试项目:https://github.com/rpuch/test-spring-injection-jdk9
它包含一个测试:MainTest
,我从我的 IDE 运行它。当我使用 JDK 8 时,它输出
сен 29, 2017 10:45:13 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5f8ed237: startup date [Fri Sep 29 22:45:13 SAMT 2017]; root of context hierarchy
OK
但在 JDK 9 下,它会在启动时抛出异常,原因如下:
Caused by: java.lang.IllegalStateException: bean1 is not injected
at Bean2.<init>(Bean2.java:7)
at Config2.bean2(Config2.java:16)
当没有注入(inject)依赖时会发生这种情况。
最佳答案
java.xml.ws.annotation
在 jdk9 中被弃用可能是您面临的问题的原因。由于注解 @Resource
来自同一模块导出的包 javax.annotation
。
您可能想提供 javatm-common-annotations作为 的可升级模块 java.xml.ws.annotation
导出 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.
关于 central suggests 的搜索,你可以使用:-
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.1</version>
</dependency>
使用您的共享代码,这在我的机器上运行良好。
此外,还有关于您共享的代码的注释。由于您正在迁移到使用 JDK9,因此您应该迁移到使用最新的 springframework依赖项 released as on 28-9-2017 :-
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
编辑:一定要看看Roman's answer如果您不打算迁移到 javaee
扩展模块,则可以使用 --add-modules
的替代方法。
关于java - Spring:@Resource 注入(inject)在 JDK9 下停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46494522/