我尝试使用@Injection
,所以从这里开始一个简单的例子:
界面
public interface NumberGenerator {
String generateNumber();
}
bookService的
public class BookServices {
@Inject
@ThirteenNumber
private NumberGenerator generator;
public Book createBook(String title){
return new Book(title, generator.generateNumber());
}
}
图书对象
public class Book {
private String title;
private String isbn;
public Book() {
}
public Book(String title, String isbn) {
this.title = title;
this.isbn = isbn;
}
//getters and setters
}
CDI
@Named(value = "injectionTest")
@ViewScoped
public class InjectionTest implements Serializable {
public void showResult() {
BookServices bookService = new BookServices();
Book book = bookService.createBook("Java book");
System.out.println(book.toString());
}
//...
}
十三号实施
@ThirteenNumber
public class IsbnGenerator implements NumberGenerator{
@Override
public String generateNumber(){
return "13-84333-" + Math.abs(new Random().nextInt());
}
}
问题
当我尝试拨打bookService.createBook("Java book")
时,它会java.lang.NullPointerException
generator.generateNumber()
,我认为它不会调用正确的@Qualifier
,试图解决此问题,使用此功能链接,Java EE 7 CDI - Injection doesn't work, sending NullPointerException我添加所有依赖项但问题仍然相同?
我错过了什么吗?
注意我知道What is a NullPointerException, and how do I fix it?
谢谢。
答案 0 :(得分:3)
问题是new BookServices()
课程中的InjectionTest
。 new
运算符会中断CDI。只需@Inject
BookServices
bean。