YCF_L YCF_L - 8 months ago 34
Java Question

JSF 2.2 - @Inject @ThirteenNumber throw NullPointException

I try to work with

@Injection
, so start with a simple example here :

Interface

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());
}
}


Book Object

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 Implementation

@ThirteenNumber
public class IsbnGenerator implements NumberGenerator{

@Override
public String generateNumber(){
return "13-84333-" + Math.abs(new Random().nextInt());
}
}


Problem

When i try to call
bookService.createBook("Java book")
it throw a
java.lang.NullPointerException
, in
generator.generateNumber()
i think it not call the right
@Qualifier
, a tried to solve this problem, using this link, Java EE 7 CDI - Injection doesn't work, sending NullPointerException i add all the dependencies but the problem still the same?

Did i miss something?

Note i know about What is a NullPointerException, and how do I fix it?

Thank you.

Answer Source

The problem is the new BookServices() in your InjectionTest class. The new operator breaks CDI. Just @Inject the BookServices bean.