Debian Codegraph @

spec/src/main/doc/architecture.asciidoc

raw
1 [[architecture]]
2 == Architecture
3
4 This specification defines a powerful set of complementary services that help improve the structure of application code.
5
6 * A well-defined lifecycle for stateful objects bound to _lifecycle contexts_, where the set of contexts is extensible
7 * A sophisticated, typesafe _dependency injection_ mechanism, including the ability to select dependencies at either development or deployment time, without verbose configuration
8 * Support for Java EE modularity and the Java EE component architecture - the modular structure of a Java EE application is taken into account when resolving dependencies between Java EE components
9 * Integration with the Unified Expression Language (EL), allowing any contextual object to be used directly within a JSF or JSP page
10 * The ability to _decorate_ injected objects
11 * The ability to associate interceptors to objects via typesafe _interceptor bindings_
12 * An _event notification_ model
13 * A web _conversation context_ in addition to the three standard web contexts defined by the Java Servlets specification
14 * An SPI allowing _portable extensions_ to integrate cleanly with the container
15
16
17 The services defined by this specification allow objects to be bound to lifecycle contexts, to be injected, to be associated with interceptors and decorators, and to interact in a loosely coupled fashion by firing and observing events. Various kinds of objects are injectable, including EJB 3 session beans, managed beans and Java EE resources. We refer to these objects in general terms as _beans_ and to instances of beans that belong to contexts as _contextual instances_. Contextual instances may be injected into other objects by the dependency injection service.
18
19 To take advantage of these facilities, the developer provides additional bean-level metadata in the form of Java annotations and application-level metadata in the form of an XML descriptor.
20
21 The use of these services significantly simplifies the task of creating Java EE applications by integrating the Java EE web tier with Java EE enterprise services. In particular, EJB components may be used as JSF managed beans, thus integrating the programming models of EJB and JSF.
22
23 It's even possible to integrate with third-party frameworks. A portable extension may provide objects to be injected or obtain contextual instances using the dependency injection service. The framework may even raise and observe events using the event notification service.
24
25 An application that takes advantage of these services may be designed to execute in either the Java EE environment or the Java SE environment. If the application uses Java EE services such as transaction management and persistence in the Java SE environment, the services are usually restricted to, at most, the subset defined for embedded usage by the EJB specification.
26
27 === Contracts
28
29 This specification defines the responsibilities of:
30
31 * the application developer who uses these services, and
32 * the vendor who implements the functionality defined by this specification and provides a runtime environment in which the application executes.
33
34
35 This runtime environment is called the _container_. For example, the container might be a Java EE container or an embeddable EJB container.
36
37 <<concepts>>, <<implementation>>, <<inheritance>>, <<interceptors>>, <<decorator_bean>> and <<observer_methods>> define the programming model for Java EE components that take advantage of the services defined by this specification, the responsibilities of the component developer, and the annotations used by the component developer to specify metadata.
38
39 <<injection_el_resolution>>, <<contexts>>, <<lifecycle>>, <<decorators>>, <<events>> and <<interceptor_resolution>> define the semantics and behavior of the services, the responsibilities of the container implementation and the APIs used by the application to interact directly with the container.
40
41 <<packaging_deployment>> defines how Java EE applications that use the services defined by this specification must be packaged into bean archives, and the responsibilities of the container implementation at application initialization time.
42
43 <<spi>>, <<contextual>> and <<context>> define an SPI that allows portable extensions to integrate with the container.
44
45 === Relationship to other specifications
46
47 An application developer creates container-managed components such as JavaBeans, EJBs or servlets and then provides additional metadata that declares additional behavior defined by this specification. These components may take advantage of the services defined by this specification, together with the enterprise and presentational aspects defined by other Java EE platform technologies.
48
49 In addition, this specification defines an SPI that allows alternative, non-platform technologies to integrate with the container and the Java EE environment, for example, alternative web presentation technologies.
50
51 ==== Relationship to the Java EE platform specification
52
53 In the Java EE 6 environment, all _component classes supporting injection_, as defined by the Java EE 6 platform specification, may inject beans via the dependency injection service.
54
55 The Java EE platform specification defines a facility for injecting _resources_ that exist in the _Java EE component environment_. Resources are identified by string-based names. This specification bolsters that functionality, adding the ability to inject an open-ended set of object types, including, but not limited to, component environment resources, based upon typesafe qualifiers.
56
57 ==== Relationship to EJB
58
59 EJB defines a programming model for application components that access transactional resources in a multi-user environment. EJB allows concerns such as role-based security, transaction demarcation, concurrency and scalability to be specified declaratively using annotations and XML deployment descriptors and enforced by the EJB container at runtime.
60
61 EJB components may be stateful, but are not by nature contextual. References to stateful component instances must be explicitly passed between clients and stateful instances must be explicitly destroyed by the application.
62
63 This specification enhances the EJB component model with contextual lifecycle management.
64
65 Any session bean instance obtained via the dependency injection service is a contextual instance. It is bound to a lifecycle context and is available to other objects that execute in that context. The container automatically creates the instance when it is needed by a client. When the context ends, the container automatically destroys the instance.
66
67 Message-driven and entity beans are by nature non-contextual objects and may not be injected into other objects.
68
69 The container performs dependency injection on all session and message-driven bean instances, even those which are not contextual instances.
70
71 ==== Relationship to managed beans
72
73 The Managed Beans specification defines the basic programming model for application components managed by the Java EE container.
74
75 As defined by this specification, most Java classes, including all JavaBeans, are managed beans.
76
77 This specification defines contextual lifecycle management and dependency injection as generic services applicable to all managed beans.
78
79 Any managed bean instance obtained via the dependency injection service is a contextual instance. It is bound to a lifecycle context and is available to other objects that execute in that context. The container automatically creates the instance when it is needed by a client. When the context ends, the container automatically destroys the instance.
80
81 The container performs dependency injection on all managed bean instances, even those which are not contextual instances.
82
83 ==== Relationship to Dependency Injection for Java
84
85 The Dependency Injection for Java specification defines a set of annotations for the declaring injected fields, methods and constructors of a bean. The dependency injection service makes use of these annotations.
86
87 ==== Relationship to Java Interceptors
88
89 The Java Interceptors specification defines the basic programming model and semantics for interceptors. This specification enhances that model by providing the ability to associate interceptors with beans using typesafe interceptor bindings.
90
91 ==== Relationship to JSF
92
93 JavaServer Faces is a web-tier presentation framework that provides a component model for graphical user interface components and an event-driven interaction model that binds user interface components to objects accessible via Unified EL.
94
95 This specification allows any bean to be assigned a name. Thus, a JSF application may take advantage of the sophisticated context and dependency injection model defined by this specification.
96
97 ==== Relationship to Bean Validation
98
99 Bean Validation provides a unified way of declaring and defining constraints on an object model, defines a runtime engine to validate objects and provides method validation.
100
101 The Bean Validation specification defines beans for Bean Validation managed objects including +Validator+ and +ValidatorFactory+. A number of Bean Validation managed instances, including ++ConstraintValidator++ s can take advantage of dependency injection. Bean Validation also provides support for method parameter validation on any bean.
102
103 === Introductory examples
104
105 The following examples demonstrate the use of lifecycle contexts and dependency injection.
106
107 ==== JSF example
108
109 The following JSF page defines a login prompt for a web application:
110
111 [source, xml]
112 ----
113 <f:view>
114 <h:form>
115 <h:panelGrid columns="2" rendered="#{!login.loggedIn}">
116 <h:outputLabel for="username">Username:</h:outputLabel>
117 <h:inputText id="username" value="#{credentials.username}"/>
118 <h:outputLabel for="password">Password:</h:outputLabel>
119 <h:inputText id="password" value="#{credentials.password}"/>
120 </h:panelGrid>
121 <h:commandButton value="Login" action="#{login.login}" rendered="#{!login.loggedIn}"/>
122 <h:commandButton value="Logout" action="#{login.logout}" rendered="#{login.loggedIn}"/>
123 </h:form>
124 </f:view>
125 ----
126
127 The Unified EL expressions in this page refer to beans named +credentials+ and +login+.
128
129 The +Credentials+ bean has a lifecycle that is bound to the JSF request:
130
131 [source, java]
132 ----
133 @Model
134 public class Credentials {
135
136 private String username;
137 private String password;
138
139 public String getUsername() { return username; }
140 public void setUsername(String username) { this.username = username; }
141
142 public String getPassword() { return password; }
143 public void setPassword(String password) { this.password = password; }
144
145 }
146 ----
147
148 The +@Model+ annotation defined in <<builtin_stereotypes>> is a _stereotype_ that identifies the +Credentials+ bean as a model object in an MVC architecture.
149
150 The +Login+ bean has a lifecycle that is bound to the HTTP session:
151
152 [source, java]
153 ----
154 @SessionScoped @Model
155 public class Login implements Serializable {
156
157 @Inject Credentials credentials;
158 @Inject @Users EntityManager userDatabase;
159
160 private CriteriaQuery<User> query;
161 private Parameter<String> usernameParam;
162 private Parameter<String> passwordParam;
163
164 private User user;
165
166 @Inject
167 void initQuery(@Users EntityManagerFactory emf) {
168 CriteriaBuilder cb = emf.getCriteriaBuilder();
169 usernameParam = cb.parameter(String.class);
170 passwordParam = cb.parameter(String.class);
171 query = cb.createQuery(User.class);
172 Root<User> u = query.from(User.class);
173 query.select(u);
174 query.where( cb.equal(u.get(User_.username), usernameParam),
175 cb.equal(u.get(User_.password), passwordParam) );
176 }
177
178 public void login() {
179
180 List<User> results = userDatabase.createQuery(query)
181 .setParameter(usernameParam, credentials.getUsername())
182 .setParameter(passwordParam, credentials.getPassword())
183 .getResultList();
184
185 if ( !results.isEmpty() ) {
186 user = results.get(0);
187 }
188
189 }
190
191 public void logout() {
192 user = null;
193 }
194
195 public boolean isLoggedIn() {
196 return user!=null;
197 }
198
199 @Produces @LoggedIn User getCurrentUser() {
200 if (user==null) {
201 throw new NotLoggedInException();
202 }
203 else {
204 return user;
205 }
206 }
207
208 }
209 ----
210
211 The +@SessionScoped+ annotation defined in <<builtin_scopes>> is a _scope type_ that specifies the lifecycle of instances of +Login+. Managed beans with this scope must be serializable.
212
213 The +@Inject+ annotation defined by the Dependency Injection for Java specification identifies an _injected field_ which is initialized by the container when the bean is instantiated, or an _initializer method_ which is called by the container after the bean is instantiated, with injected parameters.
214
215 The +@Users+ annotation is a qualifier type defined by the application:
216
217 [source, java]
218 ----
219 @Qualifier
220 @Retention(RUNTIME)
221 @Target({METHOD, FIELD, PARAMETER, TYPE})
222 public @interface Users {}
223 ----
224
225 The +@LoggedIn+ annotation is another qualifier type defined by the application:
226
227 [source, java]
228 ----
229 @Qualifier
230 @Retention(RUNTIME)
231 @Target({METHOD, FIELD, PARAMETER, TYPE})
232 public @interface LoggedIn {}
233 ----
234
235 The +@Produces+ annotation defined in <<declaring_producer_method>> identifies the method +getCurrentUser()+ as a _producer method_, which will be called whenever another bean in the system needs the currently logged-in user, for example, whenever the +user+ attribute of the +DocumentEditor+ class is injected by the container:
236
237 [source, java]
238 ----
239 @Model
240 public class DocumentEditor {
241
242 @Inject Document document;
243 @Inject @LoggedIn User currentUser;
244 @Inject @Documents EntityManager docDatabase;
245
246 public void save() {
247 document.setCreatedBy(currentUser);
248 em.persist(document);
249 }
250
251 }
252 ----
253
254 The +@Documents+ annotation is another application-defined qualifier type. The use of distinct qualifier types enables the container to distinguish which JPA persistence unit is required.
255
256 When the login form is submitted, JSF assigns the entered username and password to an instance of the +Credentials+ bean that is automatically instantiated by the container. Next, JSF calls the +login()+ method of an instance of +Login+ that is automatically instantiated by the container. This instance continues to exist for and be available to other requests in the same HTTP session, and provides the +User+ object representing the current user to any other bean that requires it (for example, +DocumentEditor+). If the producer method is called before the +login()+ method initializes the user object, it throws a +NotLoggedInException+.
257
258 ==== EJB example
259
260 Alternatively, we could write our +Login+ bean to take advantage of the functionality defined by EJB:
261
262 [source, java]
263 ----
264 @Stateful @SessionScoped @Model
265 public class Login {
266
267 @Inject Credentials credentials;
268 @Inject @Users EntityManager userDatabase;
269
270 ...
271
272 private User user;
273
274 @Inject
275 void initQuery(@Users EntityManagerFactory emf) {
276 ...
277 }
278
279 @TransactionAttribute(REQUIRES_NEW)
280 @RolesAllowed("guest")
281 public void login() {
282 ...
283 }
284
285 public void logout() {
286 user = null;
287 }
288
289 public boolean isLoggedIn() {
290 return user!=null;
291 }
292
293 @RolesAllowed("user")
294 @Produces @LoggedIn User getCurrentUser() {
295 ...
296 }
297
298 }
299 ----
300
301 The EJB +@Stateful+ annotation specifies that this bean is an EJB stateful session bean. The EJB +@TransactionAttribute+ and +@RolesAllowed+ annotations declare the EJB transaction demarcation and security attributes of the annotated methods.
302
303 ==== Java EE component environment example
304
305 In the previous examples, we injected container-managed persistence contexts using qualifier types. We need to tell the container what persistence context is being referred to by which qualifier type. We can declare references to persistence contexts and other resources in the Java EE component environment in Java code.
306
307 [source, java]
308 ----
309 public class Databases {
310
311 @Produces @PersistenceContext(unitName="UserData")
312 @Users EntityManager userDatabaseEntityManager;
313
314 @Produces @PersistenceUnit(unitName="UserData")
315 @Users EntityManagerFactory userDatabaseEntityManagerFactory;
316
317 @Produces @PersistenceContext(unitName="DocumentData")
318 @Documents EntityManager docDatabaseEntityManager;
319
320 }
321 ----
322
323 The JPA +@PersistenceContext+ and +@PersistenceUnit+ annotations identify the JPA persistence unit.
324
325 ==== Event example
326
327 Beans may raise events. For example, our +Login+ class could raise events when a user logs in or out.
328
329 [source, java]
330 ----
331 @SessionScoped @Model
332 public class Login implements Serializable {
333
334 @Inject Credentials credentials;
335 @Inject @Users EntityManager userDatabase;
336
337 @Inject @LoggedIn Event<User> userLoggedInEvent;
338 @Inject @LoggedOut Event<User> userLoggedOutEvent;
339
340 ...
341
342 private User user;
343
344 @Inject
345 void initQuery(@Users EntityManagerFactory emf) {
346 ...
347 }
348
349 public void login() {
350
351 List<User> results = ... ;
352
353 if ( !results.isEmpty() ) {
354 user = results.get(0);
355 userLoggedInEvent.fire(user);
356 }
357
358 }
359
360 public void logout() {
361 userLoggedOutEvent.fire(user);
362 user = null;
363 }
364
365 public boolean isLoggedIn() {
366 return user!=null;
367 }
368
369 @Produces @LoggedIn User getCurrentUser() {
370 ...
371 }
372
373 }
374 ----
375
376 The method +fire()+ of the built-in bean of type +Event+ defined in <<event>> allows the application to fire events. Events consist of an _event object_ - in this case the +User+ - and event qualifiers. Event qualifier - such as +@LoggedIn+ and +@LoggedOut+ - allow event consumers to specify which events of a certain type they are interested in.
377
378 Other beans may observe these events and use them to synchronize their internal state, with no coupling to the bean producing the events:
379
380 [source, java]
381 ----
382 @SessionScoped
383 public class Permissions implements Serializable {
384
385 @Produces
386 private Set<Permission> permissions = new HashSet<Permission>();
387
388 @Inject @Users EntityManager userDatabase;
389 Parameter<String> usernameParam;
390 CriteriaQuery<Permission> query;
391
392 @Inject
393 void initQuery(@Users EntityManagerFactory emf) {
394 CriteriaBuilder cb = emf.getCriteriaBuilder();
395 usernameParam = cb.parameter(String.class);
396 query = cb.createQuery(Permission.class);
397 Root<Permission> p = query.from(Permission.class);
398 query.select(p);
399 query.where( cb.equal(p.get(Permission_.user).get(User_.username),
400 usernameParam) );
401 }
402
403 void onLogin(@Observes @LoggedIn User user) {
404 permissions = new HashSet<Permission>( userDatabase.createQuery(query)
405 .setParameter(usernameParam, user.getUsername())
406 .getResultList() );
407 }
408
409 void onLogout(@Observes @LoggedOut User user {
410 permissions.clear();
411 }
412
413
414 }
415 ----
416
417 The +@Produces+ annotation applied to a field identifies the field as a producer field, as defined in <<producer_field>>, a kind of shortcut version of a producer method. This producer field allows the permissions of the current user to be injected to an injection point of type +Set<Permission>+.
418
419 The +@Observes+ annotation defined in <<observes>> identifies the method with the annotated parameter as an _observer method_ that is called by the container whenever an event matching the type and qualifiers of the annotated parameter is fired.
420
421 ==== Injection point metadata example
422
423 It is possible to implement generic beans that introspect the injection point to which they belong. This makes it possible to implement injection for ++Logger++ s, for example.
424
425 [source, java]
426 ----
427 class Loggers {
428
429 @Produces Logger getLogger(InjectionPoint injectionPoint) {
430 return Logger.getLogger( injectionPoint.getMember().getDeclaringClass().getSimpleName() );
431 }
432
433 }
434 ----
435
436 The +InjectionPoint+ interface defined in <<injection_point>>, provides metadata about the injection point to the object being injected into it.
437
438 Then this class will have a +Logger+ named +"Permissions"+ injected:
439
440 [source, java]
441 ----
442 @SessionScoped
443 public class Permissions implements Serializable {
444
445 @Inject Logger log;
446
447 ...
448
449 }
450 ----
451
452 ==== Interceptor example
453
454 _Interceptors_ allow common, cross-cutting concerns to be applied to beans via custom annotations. Interceptor types may be individually enabled or disabled at deployment time.
455
456 The +AuthorizationInterceptor+ class defines a custom authorization check:
457
458 [source, java]
459 ----
460 @Secure @Interceptor
461 public class AuthorizationInterceptor {
462
463 @Inject @LoggedIn User user;
464 @Inject Logger log;
465
466 @AroundInvoke
467 public Object authorize(InvocationContext ic) throws Exception {
468 try {
469 if ( !user.isBanned() ) {
470 log.fine("Authorized");
471 return ic.proceed();
472 }
473 else {
474 log.fine("Not authorized");
475 throw new NotAuthorizedException();
476 }
477 }
478 catch (NotAuthenticatedException nae) {
479 log.fine("Not authenticated");
480 throw nae;
481 }
482 }
483
484 }
485 ----
486
487 The +@Interceptor+ annotation, defined in <<declaring_interceptor>>, identifies the +AuthorizationInterceptor+ class as an interceptor. The +@Secure+ annotation is a custom _interceptor binding type_, as defined in <<interceptor_bindings>>.
488
489 [source, java]
490 ----
491 @Inherited
492 @InterceptorBinding
493 @Target({TYPE, METHOD})
494 @Retention(RUNTIME)
495 public @interface Secure {}
496 ----
497
498 The +@Secure+ annotation is used to apply the interceptor to a bean:
499
500 [source, java]
501 ----
502 @Model
503 public class DocumentEditor {
504
505 @Inject Document document;
506 @Inject @LoggedIn User user;
507 @Inject @Documents EntityManager em;
508
509 @Secure
510 public void save() {
511 document.setCreatedBy(currentUser);
512 em.persist(document);
513 }
514
515 }
516 ----
517
518 When the +save()+ method is invoked, the +authorize()+ method of the interceptor will be called. The invocation will proceed to the +DocumentEditor+ class only if the authorization check is successful.
519
520 ==== Decorator example
521
522 _Decorators_ are similar to interceptors, but apply only to beans of a particular Java interface. Like interceptors, decorators may be easily enabled or disabled at deployment time. Unlike interceptors, decorators are aware of the semantics of the intercepted method.
523
524 For example, the +DataAccess+ interface might be implemented by many beans:
525
526 [source, java]
527 ----
528 public interface DataAccess<T, V> {
529
530 public V getId(T object);
531 public T load(V id);
532 public void save(T object);
533 public void delete(T object);
534
535 public Class<T> getDataType();
536
537 }
538 ----
539
540 The +DataAccessAuthorizationDecorator+ class defines the authorization checks:
541
542 [source, java]
543 ----
544 @Decorator
545 public abstract class DataAccessAuthorizationDecorator<T, V> implements DataAccess<T, V> {
546
547 @Inject @Delegate DataAccess<T, V> delegate;
548
549 @Inject Logger log;
550 @Inject Set<Permission> permissions;
551
552 public void save(T object) {
553 authorize(SecureAction.SAVE, object);
554 delegate.save(object);
555 }
556
557 public void delete(T object) {
558 authorize(SecureAction.DELETE, object);
559 delegate.delete(object);
560 }
561
562 private void authorize(SecureAction action, T object) {
563 V id = delegate.getId(object);
564 Class<T> type = delegate.getDataType();
565 if ( permissions.contains( new Permission(action, type, id) ) ) {
566 log.fine("Authorized for " + action);
567 }
568 else {
569 log.fine("Not authorized for " + action);
570 throw new NotAuthorizedException(action);
571 }
572 }
573
574 }
575 ----
576
577 The +@Decorator+ annotation defined in <<decorator_annotation>> identifies the +DataAccessAuthorizationDecorator+ class as a decorator. The +@Delegate+ annotation defined in <<delegate_attribute>> identifies the _delegate_, which the decorator uses to delegate method calls to the container. The decorator applies to any bean that implements +DataAccess+.
578
579 The decorator intercepts invocations just like an interceptor. However, unlike an interceptor, the decorator contains functionality that is specific to the semantics of the method being called.
580
581 Decorators may be declared abstract, relieving the developer of the responsibility of implementing all methods of the decorated interface. If a decorator does not implement a method of a decorated interface, the decorator will simply not be called when that method is invoked upon the decorated bean.
582