I am setting up basic environment for learning CDI in JavaEE7. I have the following code for starting Weld. Just a startup and shutdown.
package
To set up a learning CDI environment, all you need is a CDI implementation such as the Weld reference implementation; you don't need a Java EE container.
The easy way is to create a maven project with a dependency in pom.xml:
(Make sure to create an empty or the minimal beans.xml file in META-INF directory before you run the java application. If you go for maven, you can create META-INF in the src/main/resources directory)
org.jboss.weld.se
weld-se
2.3.4.Final
Here's the application:
public class CdiApplication {
private Weld weld;
private WeldContainer container;
private BookService bookService;
private void init() {
weld = new Weld();
container = weld.initialize();
BookService = container.instance().select(BookService.class).get();
}
private void start() {
Book book = bookService.createBook("My title", "My description", 23.95);
System.out.println(book);
}
private void shutdown() {
weld.shutdown();
}
public static void main(String[] args) {
CdiApplication application = new CdiApplication();
application.init();
application.start();
application.shutdown();
}
}
The Book class:
public class Book { // Book is a POJO
private String title;
private String description;
private double price;
private String id; // ISBN or ISSN
private Date instanciationDate;
public Book() { // default constructor
}
public Book(String title, String description, double price) {
this.title = title;
this.description = description;
this.price = price;
// the BookService is responsible to set the id (ISBN) and date fields.
}
// setters and getters
// toString method
}
And the BookService class to create an book and set its instanciation date and id (ISBN) using the injected NumberGenerator:
public class BookService {
@Inject
private NumberGenerator numberGenerator;
private Date instanciationDate;
@PostConstruct
private void setInstanciationDate() {
instanciationDate = new Date();
}
public Book createBook(String title,
String description, double price) {
Book book = new Book(title, description, price);
book.setId(numberGenerator.generateNumber());
book.setDate(instanciationDate);
return book;
}
}
In a servlet environment, the servlet container will responsible to bootstrap the CDI, meaning that you have to deploy your "web application" on a Java EE container such as Tomcat or Wildfly.