Understanding
Context & Dependency Injection
Antonio Goncalves
www.antoniogoncalves.org
@agoncal
Module Outline
What is injection?
Injection is delegated to a container
What is Context & Dependency Injection?
What it is not!
Where do we inject objects?
Injecting objects
Java SE
Java EE
What Is Dependency Injection?
Objects don’t create their dependencies
Factories
Dependencies passed on constructors…
… or setters
Can be complex
Something else does
Dependency injector
Container
Provider
What Is a Container?
Runtime environment Container
Components
Services
Provides certain services
Life-cycle management
Dependency injection
Interception
Component
Concurrency
Security
Inversion of control (IoC)
Managed environment
Managed beans
What Is a Managed Bean?
Bean managed by a container
Java SE
Objects
JVM is a container
Class loading
Garbage collection…
Java EE
Servlets
Servlet container
HTTP handling
Pooling…
What Is Context and Dependency Injection?
Runtime environment Bean Manager
CDI Beans
Services
CDI services
Dependency injection
Interception
Decoration Injection
Bean
Event handling
Context management
Bean
What Isn’t Context and Dependency Injection?
Not a full Java EE container
Doesn’t manage a Servlet, REST web service…
No HTTP
No Transactions
…
Extensions
Extend the container services
A Brief of History of CDI
Dependency injection has been around for a long time
Commercial and open source products
Spring, Seam, Guice…
Successful but not standardized
CDI 1.0 in 2009 (Java EE 6)
CDI 1.1 in 2013 (Java EE 7)
CDI 1.2 in 2014
CDI 2.0 in Java EE 8
CDI Specification
Specification
JSR 346
http://jcp.org/en/jsr/detail?id=346
CDI Implementations
Runtime
Implement the JSR 346
Weld
Open WebBeans
CanDI
No vendor locking
DeltaSpike
Not a CDI implementation
Apache open source project
Enriches the CDI ecosystem
CDI portable extension
Extra services
Security
Configuration
Scheduling
Declarative queries for JPA
…
CDI Packages
Package Description
javax.inject Core dependey injection API
javax.enterprise.inject Core CDI API
javax.enterprise.context Scopes and contextual APIs
javax.enterprise.event Events and observers APIs
javax.interceptor Interceptor APIs
javax.decorator Decorator APIs
javax.enterprise.util CDI utility package
Where Can We Use CDI?
Java SE Java EE
What is a CDI Bean?
Concrete class
Default constructor
Doesn’t need to:
Implement interface
Extend a class
Be annotated
Can have optional
Qualifiers
Scope
Expression language name
Interceptor bindings
A CDI Bean
@ThirteenDigits
public class IsbnGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}
A CDI Bean
@Interceptor
public class IsbnGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}
A CDI Bean
@Decorator
public class IsbnGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}
A CDI Bean
@Named
public class IsbnGenerator {
public String generateNumber() {
return "13-84356-" + Math.abs(new Random().nextInt());
}
}
Life Cycle of a CDI Bean
Lifecycle of a POJO
Create an instance with new
Garbage collector
CDI beans are managed by a container
The container creates the instance
Gets rid of it
Manages the life cycle
Handle
After construction
Before destruction
Life Cycle of a CDI Bean
new IsbnGenerator() Garbage collected
Exists
Dependency injection
@PostConstruct @PreDestroy
Managed
Method invocations
Callback Annotations
@PreDestroy
@PostConstruct
Public, private, protected, package-level
Cannot be static or final
Throw unchecked exceptions
CDI Bean with Callback Annotations
public class IsbnGenerator {
private int postfix;
@PostConstruct
private void init () {
postfix = Math.abs(new Random().nextInt());
}
public String generateNumber() {
return "13-84356-" + postfix++;
}
}
Injecting a CDI Bean
public class BookService {
Injection Point
@Inject
private NumberGenerator generator;
public Book createBook(String title) {
return new Book(title, generator.generateNumber());
}
}
Injecting a CDI Bean
public class BookService {
@Inject("thirteenDigits")
private NumberGenerator generator;
public Book createBook(String title) {
return new Book(title, generator.generateNumber());
}
}
Injecting a CDI Bean
public class BookService {
@Inject @ThirteenDigits
private NumberGenerator generator;
public Book createBook(String title) {
return new Book(title, generator.generateNumber());
}
}
Deployment Descriptor
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<alternatives>
<class>com.pluralsight.MockGenerator</class>
</alternatives>
<interceptors>
<class>com.pluralsight.LoggingInterceptor</class>
</interceptors>
</beans>
beans.xml
Bean Discovery
Searches for beans
Bean archives
Application classpath Bean
Detects definition errors
Bean
Bean
Exceptions cancel deployment
Bean
Application not available
Bean
Injection points are referenced
Bean
Up and running
Bean Archive
CDI beans in JARs or WARs app.war
Bean archive a.jar
Annotated beans AnnotatedBean.class
bean-discovery-mode="all"
b.jar
Archive NoAnnotatedBean.class
beans.xml ="all"
None annotated beans
bean-discovery-mode="none"
c.jar
NoAnnotatedBean.class
d.jar
AnnotatedBean.class
beans.xml ="none"
Where Can We Use CDI?
Business Model
@Entity
@EntityListener(Validation.class)
public class Book {
@Id @GeneratedValue
private Long id;
@NotNull @Title
private String title;
Business Logic
public class BookService {
@Inject
private NumberGenerator generator;
public Book createBook(String title) {...}
}
Presentation
@Named
@SessionScoped
public class BookBean {
@Inject
private BookService service;
public String createBook() {...}
}
Client
public class BookComponent {
@Inject
private BookService service;
public void displayBook() {...}
}
Interoperability
@Path("/book")
public class BookEndpoint {
@Inject
private BookService service;
@GET
public List<Book> getAllBooks() {...}
}
CDI in Our Tiered Architectures
public class BookService { }
@Named @Entity
@SessionScoped @EntityListeners
public class BookBean { } public class Book { }
@Path("/book")
public class BookEndpoint { }
Summary
What is injection?
What is CDI?
How to develop a CDI bean
How to inject a CDI bean
CDI in n-tier architecture