-3

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.

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    The problem is the `new BookServices()` in your InjectionTest class. The `new` operator breaks CDI. Just `@Inject` the `BookServices` – Rouliboy Apr 13 '17 at 08:37
  • thank you @Rouliboy this is really was helpful, i get another error after that `CDI deployment failure:WELD-001408: Unsatisfied dependencies for type BookServices with qualifiers @Default` i solved it like this 1- implements Serializable in BookServices and change `bean-discovery-mode` to `bean-discovery-mode="all"` thank you so much again – Youcef LAIDANI Apr 13 '17 at 08:51

1 Answers1

3

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

Rouliboy
  • 1,377
  • 1
  • 8
  • 21