To set up a CDI learning environment, you only need a CDI implementation, such as the Weld reference implementation; You do not need a Java EE container.
An easy way is to create a maven project with a dependency in pom.xml : (Be sure to create an empty or minimal beans.xml file in the META-INF before running the java application. If you switch to maven, you can create META-INF in the src/main/resources directory src/main/resources )
<dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se</artifactId> <version>2.3.4.Final</version> </dependency>
Here is 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(); } }
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 for creating a book and setting its initialization date and identifier (ISBN) using the NumberGenerator entered:
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 is responsible for loading the CDI, which means that you need to deploy your "web application" in a Java EE container such as Tomcat or Wildfly.
alix
source share