0% found this document useful (0 votes)
8 views

7 Context Dependency Injection 1 1 m7 Slides

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

7 Context Dependency Injection 1 1 m7 Slides

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

CDI 1.

1 within Java EE 7

Antonio Goncalves
www.antoniogoncalves.org
@agoncal
Module Outline


 Java Enterprise Edition 7

 Services given by the Java EE container

 CDI integration
 JSF
 Transactional components
 JPA
 Bean Validation

 Summary

 References

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Quick Overview of Java EE 7

 Java Enterprise Edition


 Umbrella specification
 JSR 342
 Contains 32 specifications
 Make them work together

 Java EE 7 is a managed environment


 Container
 Providers

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Main Java EE 7 Specifications

JSF 2.2 JSP JSTL EL 3.0 JAX-RS 2.0


Bean Validation 1.1

Concurrency 1.0
Interceptors 1.2

JSON-P 1.0
Servlet 3.1 Web Socket 1.0
CDI 1.1

Batch 1.0
JTA 1.2 EJB 3.2 JMS 2.0
JavaMail 1.5

JPA 2.1 JCA 1.7

Java EE 7

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
CDI Interactions in Java EE 7

JSF 2.2 JSP JSTL EL 3.0 JAX-RS 2.0


Bean Validation 1.1

Concurrency 1.0
Interceptors 1.2

JSON-P 1.0
Servlet 3.1 Web Socket 1.0
CDI 1.1

Batch 1.0
JTA 1.2 EJB 3.2 JMS 2.0
JavaMail 1.5

JPA 2.1 JCA 1.7

Java EE 7

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Integration with Java EE

 Java EE is a superset container

 CDI a subset container

 Java EE container controls life-cycle of CDI container

 Bootstraps the BeanManager

 Automatic in Java EE

 Programmatic in Java SE


No standard API yet
Deltaspike
Standardized in CDI 2.0

Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Bootstrapping CDI in Java SE
public class BookService {

public Book createBook(String title) {


CdiContainer container =
CdiContainerLoader.getCdiContainer();
container.boot();
BeanManager manager = container.getBeanManager();
Set<Bean<?>> beans =
manager.getBeans(NumberGenerator.class);
Bean<?> bean = manager.resolve(beans);
NumberGenerator generator = (NumberGenerator)
manager.getReference(bean, NumberGenerator.class);

return new Book(title, generator.generateNumber());


Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Java EE Bootstraps CDI
public class BookService {

@Inject
private NumberGenerator generator;

public Book createBook(String title) {


CdiContainer container =
CdiContainerLoader.getCdiContainer();
container.boot();
BeanManager manager = container.getBeanManager();
Set<Bean<?>> beans =
manager.getBeans(NumberGenerator.class);
Bean<?> bean = manager.resolve(beans);
NumberGenerator generator = (NumberGenerator)
manager.getReference(bean, NumberGenerator.class);

return new Book(title, generator.generateNumber());


Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Integration with JSF

 Java Server Faces (JSF)

 Backing beans


 CDI services
 CDI scopes
 @ViewScoped
 @FlowScoped

 Facelets pages
 Expression language
 @Named

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JSF Backing Bean
@Named
@RequestScoped

public class CustomerBean implements Serializable {

public String doCreate() {

service.create(firstName, lastName, email);


return null;
}
}
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JSF Backing Bean
@Named
@ConversationScoped
@Loggable
public class CustomerBean implements Serializable {

@Inject
private CustomerService service;

@Inject
private Conversation conversation;

public String doCreate() {


conversation.begin();
service.create(firstName, lastName, email);
return null;
}
}
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JSF Page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>

<h:outputLabel value="Name:"/>
<h:inputText value="#{customerBean.customer.name}"/>
<h:outputLabel value="Email:"/>
<h:inputText value="#{customerBean.customer.email}"/>
<h:commandLink value="Create"
action='#{customerBean.doCreate}'/>
</h:form>
</h:body>
</html>

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Integration with EJB

 Enterprise Java Bean (EJB)


 Process business logic
 Transactional
 Secure

 Stateless
 Request scope

 Stateful
 Choose from application, session, conversation scope

 EJB and CDI are very closed

 Inject an EJB with @Inject


Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Stateless EJB
@Stateless

public class BookService {

@PersistenceContext(unitName = "myPU")
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@PostConstruct
private void init () {...}

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Stateless EJB
@Stateless

public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@PostConstruct
private void init () {...}

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Stateful EJB
@Stateful
@SessionScoped
public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@PostConstruct
private void init () {...}

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
@Transactional

 @Transactional interceptor binding

 Belongs to the JTA specification


 Java Transaction API
 JSR 907

 Class or method level

 Controls transaction boundaries

 On any Java EE managed bean


 CDI Bean
 REST endoint
 JSF backing bean
 Servlet Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Transactional Bean
@Stateless

public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@PostConstruct
private void init () {...}

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Transactional Bean
@Transactional

public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@PostConstruct
private void init () {...}

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Transactional REST Endpoint
@Transactional
@Path("book")
public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

@POST
@Consumes(MediaType.APPLICATION_XML)
public Book createBook(Book book) {
bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Transactional JSF Backing Bean
@Transactional
@Named
public class BookService {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Transactional Servlet
@Transactional
@WebServlet(urlPatterns={"/TxServlet"})
public class BookService extends HttpServlet {

@Inject
private EntityManager em;

@Inject @Paper(SECOND_HAND)
private Event<Book> bookEvent;

public Book createBook(Book book) {


bookEvent.fire(book);
em.persist(book);
return book;
Do Not Place Anything
} in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Integration with JPA

 Java Persistence API (JPA)


 Object-relational mapping

 No SQL manipulation

 JPA doesn’t fit with CDI

 Different lifecycles

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Life Cycle of a CDI Bean

Exists

Managed

Method invocations
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Life Cycle of a JPA Entity

Transient

Detached Managed Removed

Do Not Place Anything


in This Space
Database (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JPA Entities are not CDI Beans
@Entity

public class Author {

@Id @GeneratedValue
private Long id;
private String firstName;
//...
}

public class AuthorService {


@Inject
private Author author;
Do Not Place Anything
//... in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JPA Entities are not CDI Beans
@Entity

public class Author {

@Inject
private Logger logger;

@Id @GeneratedValue
private Long id;
private String firstName;
//...
}

public class AuthorService {

private Author author = new Author();


Do Not Place Anything
//... in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JPA Entities are not CDI Beans
@Entity
@EntityListeners({DebugListener.class})
public class Author {

@Id @GeneratedValue
private Long id;
private String firstName;
//...
}

public class AuthorService {

private Author author = new Author();


Do Not Place Anything
//... in This Space
} (Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
JPA Listeners are CDI Beans
public class DebugListener {

@Inject
private Logger logger;

@PrePersist
private void prePersist(Object object) {
logger.debug("Object persisted {})", object);
}
}

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Bean Validation

 Process, store, retrieve data


 Constrain our model
 Is the address valid?
 Is the email well formed?
 Is the customer's name null?
 Is the birthday in the past?


 Ensure data is valid

 Annotations

 Validators
 CDI beans
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Validators are CDI Beans
public class NotNullValidator implements
ConstraintValidator<NotNull, Object> {

@Inject
private Logger logger;

@Override
public void initialize(NotNull parameters) { }

@Override
public boolean isValid(Object object,
ConstraintValidatorContext context) {
logger.debug("Null object {})", object);
return object != null;
}
}
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Injecting a Validator
public class BookService {

@Inject
private Validador validator;

public Book validateBook(Book book) {

Set<ConstraintViolation<Book>> violations;
violations = validator.validate(book);
if (violations.size() > 0)
throw new ConstraintViolationException(violations);
}
}

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Summary

 Introduction


 Understanding Context & Dependency Injection

 Dependency Injection

 Producers and Disposers

 Interceptors, Decorators and Events

 Bringing the Web Tier and Service Tier Together

 Context & Dependency Injection 1.1 within Java EE 7

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Design Patterns

 Dependency injection


 Bridge (with alternatives)

 Factory (with producers)

 Interceptor

 Decorator

 Observer/observable (with events)

 Tool box
 Ease business applications development
 Enrich technical frameworks
Do Not Place Anything
in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
References

 CDI 1.1 specification


 JSR 346
 http://jcp.org/en/jsr/detail?id=346

 Java EE 7 specification
 JSR 342
 http://jcp.org/en/jsr/detail?id=342

 Pluralsight courses
 Bean Validation
 Java Persistence API (JPA)

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Java EE 7 Book

Do Not Place Anything


in This Space
(Add watermark during
editing)
Note: Warning will not appear
during Slide Show view.
Context & Dependency Injection 1.1
Decouple Components with CDI

Antonio Goncalves
www.antoniogoncalves.org
@agoncal

You might also like