@Inject字段始终为null [英] @Inject field is always null
问题描述
我尝试@Inject一个字段(它是一个jar模块,空的beans.xml存在于META-INF下),如下所示:
I try to @Inject a field (its a jar module, empty beans.xml is existing under META-INF) like this:
IDataProvider Interface
IDataProvider Interface
public interface IDataProvider {
void test();
}
DataProvider实现
import javax.enterprise.context.ApplicationScoped;
DataProvider implementation import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class DataProvider implements IDataProvider {
private int i;
public DataProvider() {
i = 42;
}
@Override
public void test() {
}
}
我尝试注入DataProvider的类
And the class where i try to inject the DataProvider
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class DataController {
@Inject
private IDataProvider dataProvider;
private int k;
public DataController() {
k = 42;
}
}
如果我在Wildfly上运行它,注入的dataProvider总是null(DataController构造函数中的断点)。
If i run this on Wildfly the injected dataProvider is always null (Breakpoint at DataController constructor).
在每个教程上都是这样做的,所以我认为这应该有效。唯一的区别是两个类都应该是@ApplicationScoped
On every tutorial it's done like this, so i thought this should work. Only difference is that both classes should be @ApplicationScoped
我正在使用Wildfly 8.2Final,Gradle,IntelliJ。
我的gradle.build看起来像这样:
I am using Wildfly 8.2Final, Gradle, IntelliJ. My gradle.build looks like this:
apply plugin: 'java'
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile group:'javax', name:'javaee-web-api', version:'7.+'
compile group:'org.jboss.ejb3', name:'jboss-ejb3-ext-api', version:'2.+'
}
sourceSets {
main {
java {
srcDir 'src/api/java'
srcDir 'src/main/java'
}
}
test {
java {
srcDir 'src/test/java'
}
}
}
jar {
from ('./src') {
include 'META-INF/beans.xml'
}
}
有没有人知道为什么这不起作用?我没有从Wildfly获得任何错误或异常。
Does anyone have an idea why this is not working? i dont get any error or exception from Wildfly.
推荐答案
在构建 DataController期间
, dataProvider
为空是正常的。在此之后进行注入。
During the construction of the DataController
, it's normal the dataProvider
is null. Injection happens after that.
您应该添加 @PostConstruct
方法来检查字段的无效性:
You should add a @PostConstruct
method to check for nullity of the field:
@PostConstruct
void init() {
// dataProvider should not be null here.
}
另外,Weld的错误报告工作做得非常好。因此,如果注入失败,您应该有一个明确而详细的错误消息,而不仅仅是一个空字段。
Aditionally, error reporting on Weld is pretty well done. So you should have an explicit and detailed error message if the injection fails, and not only a null field.
这篇关于@Inject字段始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!