當我嘗試在枚舉中注入Logger生產者時,我得到了一個NPE。我怎樣才能在一個枚舉中注入一個記錄器?如何在枚舉中注入記錄器
例子:
public enum MyEnum {
HI("Hi there!"),
HELLO("Hello mister!");
@Inject
private Logger log;
private final String greeting;
private MyEnum(String greeting) {
this.greeting = greeting;
// this.log = LoggerFactory.getLogger(this.getClass());
}
public String getGreeting() {
log.debug("Method getGreeting called");
return this.greeting;
}
}
該類給我的log.debug()
線NPE。當我刪除@Inject
並取消註釋this.log
行它的作品。
測試用例看起來是這樣的:
對於這個問題@RunWith(Arquillian.class)
public class CoverKindTest {
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClass(MyEnum.class)
.addClass(LoggerProducer.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
public void testEnum() {
MyEnum myEnum = MyEnum.HI;
String greeting = myEnum.getGreeting();
assertThat("Should give the greeting.", greeting, is("Hi there!"));
}
}
完全可測試的項目都可以在這裏找到,MyEnum.class
是原來的問題,MyEnum1.class
是沒有注射液(工作,但不是我期待的)和MyEnum2.class
是一個建議的答案。
編輯:用工作解決方案更新了GitHub倉庫。 https://github.com/martijnburger/how-to-inject-a-logger-in-an-enum
我想原因是你使用CDI注入記錄儀,它不起作用,因爲你的枚舉不是一個bean =>你的記錄器保持爲空。 –
你怎麼稱呼枚舉?對於注入來使用它所使用的類應該是代理創建的對象。我猜你正在直接調用'MyEnum.HI.getGreeting()',在這種情況下,相應的DI框架將不知道它需要注入一些變量。你可以粘貼你如何調用這個代碼? –
@BandiKishore是的,這就是我使用它的方式。我添加了測試用例。有沒有辦法使用'LoggerProducer'來登錄這種情況? –