The document discusses contexts and dependency injection in the Java EE 6 ecosystem. It provides an overview of key concepts of the Contexts and Dependency Injection (CDI) specification such as type-safe dependency injection, loose coupling, context and scope management, producer methods, interceptors, decorators, and events. It also discusses how CDI integrates with and enhances other Java EE technologies like EJB, JSF, JPA, JAX-RS and JAX-WS.
In this Java Spring Training session, you will learn Spring AOP – Aspect Oriented Programming Topics covered in this session are:
For more information, visit this link:
• Auto-wiring
• Annotations based configuration
• Java based configuration
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
In this core java training session, you will learn Java IO – Files, Streams and
Object Serialization. Topics covered in this session are:
• Java IO
• Files
• Streams
• Byte-based
• Character-based
• Object Serialization
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
In this Java Spring Training session, you will learn Spring AOP – Aspect Oriented Programming Topics covered in this session are:
For more information, visit this link:
• Auto-wiring
• Annotations based configuration
• Java based configuration
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
In this core java training session, you will learn Java IO – Files, Streams and
Object Serialization. Topics covered in this session are:
• Java IO
• Files
• Streams
• Byte-based
• Character-based
• Object Serialization
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
Designing Java EE Applications in the Age of CDIMichel Graciano
Â
Even though CDI has been available since the end of 2009, most people still do not realize its full power and the possibilities it brings. Attend this session to understand which CDI features make it excel in comparison with other dependency-injection-based solutions and see how they can be used to design flexible applications and frameworks that will stand the test of time.
Dependency injection design pattern is introduced in order to solve some common issues due to explicit wiring between a component and its collaborator or service.
Spring Framework and AngularJS are involved to show how dependency injection could simplify the way of writing code but above all testing.
Clean and concise code is obtained using DI. Real example are provided on Github and Plunkr.
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
Â
As the adoption of Contexts and Dependency Injection (CDI) for Java EE API grows, it is important to understand how to use CDI effectively to maximize the benefits of using a loosely coupled, type-safe, annotation-driven dependency injection solution. This session outlines the best practices for using CDI, such as annotations versus XML, @Named as a qualifier, qualifier type safety versus verbosity, effective use of producers/disposers, using scopes properly, best practices for using conversations, defining effective stereotypes, interceptors versus decorators, static versus dynamic injection/lookup, CDI versus Java EE resource injection, using CDI with EJB 3.1, CDI/JSF 2 integration patterns, and CDI/JPA 2 usage patterns.
Make JSF more type-safe with CDI and MyFaces CODIos890
Â
These slides show how to use type-safe mechanisms provided by MyFaces CODI for developing JSF applications which are more type-safe and easier to maintain.
http://2012.con-fess.com/sessions/-/details/136/MyFaces-CODI-and-JBoss-Seam3-become-Apache-DeltaSpike is the next part with more details about MyFaces CODI and Apache DeltaSpike at
First lecture in the Java EE training course.
Covers:
- Java EE project setup
- Introduction to Maven
- Web application structure
- JSF basics
- CDI basics
Unleash the power of Context and Dependency Injection (CDI) in a JEE container. The slides go over the 2.0 specification and how each part of the specification can be applied. Code for this can be found on GitHub: https://github.com/bpaskin/JavaExamples/tree/master/CDI2.0Examples/src/com/ibm/example/cdi
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Miguel Gallardo
Â
Frameworks are very helpful to solve common problems when developing an application. But what happens when we have to move to another framework? In this talk I will show how my company tries to keep independent of any framework, decoupling our business logic from symfony.
5 Skills To Force Multiply Technical Talents.pdfArun Gupta
Â
This talk explains what are non-technical skills, why they are relevant, and what are some of the most important skills to master to force multiply your technical talent.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
Â
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
Â
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
Â
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
Â
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Â
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
Â
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
DevOps and Testing slides at DASA ConnectKari Kakkonen
Â
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
Â
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Â
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
Â
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Â
Using Contexts & Dependency Injection in the Java EE 6 Platform
1. <Insert Picture Here>
Contexts And Dependency Injection In The Java EE 6 Ecosystem
Arun Gupta
Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta
4. The following is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality,
and should not be relied upon in making purchasing
decisions.
The development, release, and timing of any features or
functionality described for Oracle’s products remains at the
sole discretion of Oracle.
4
5. How we got here ?
• Java EE 5 had resource injection
– @EJB, @PersistenceUnit, @Resource
• Motivated by Seam, Guice, and Spring
– More typesafe than Seam
– More stateful and less XML-centric than Spring
– More web and enterprise-capable than Guice
• Adapts JSR 330 for Java EE environments
– @Inject, @Qualifier, @ScopeType
5
6. CDI Key Concepts
• Type-safe approach to Dependency Injection
• Strong typing, Loose coupling
– Events, Interceptors, Decorators
• Context & Scope management
• Works with Java EE modular and component architecture
– Integration with Unified Expression Language (UEL)
• Portable extensions
• Bridge EJB (transactional tier) and JSF (presentation tier) in
the platform
6
7. What is a CDI managed bean ?
• “Beans”
– All managed beans by other Java EE specifications
• Except JPA
– Meets the following conditions
• Non-static inner class
• Concrete class or decorated with @Decorator
• Constructor with no parameters or a constructor annotated with @Inject
• “Contextual instances” - Instances of “beans” that belong to
contexts
7
8. How to configure ?
There is none!
• Discovers bean in all modules in which CDI is enabled
• “beans.xml”
– WEB-INF of WAR
– META-INF of JAR
– META-INF of directory in the classpath
• Can enable groups of bean selectively via a descriptor
8
9. Injection Points
• Field, Method, Constructor
• 0 or more qualifiers
Which one ?
• Type (Qualifier)
@Inject @LoggedIn User user
Request What ?
Injection (Type)
9
10. Basic – Sample Code
public interface Greeting {
public String sayHello(String name); Default “dependent”
scope
}
public class HelloGreeting implements Greeting {
public String sayHello(String name) {
return “Hello “ + name;
}
}
@Stateless
public class GreetingService {
@Inject Greeting greeting;
public String sayHello(String name) { No String identifiers,
return greeting.sayHello(name); All Java
}
}
10
11. Qualifier
• Annotation to uniquely identify a bean to be injected
• Built-in qualifiers
– @Named required for usage in EL
– @Default qualifier on all beans marked with/without @Named
– @Any implicit qualifier for all beans (except @New)
– @New
11
12. Qualifier – Sample Code
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Texan {
}
@Texan
public class HowdyGreeting implements Greeting {
public String sayHello(String name) {
return “Howdy “ + name;
}
}
@Stateless
public class GreetingService {
@Inject @Texan Greeting greeting;
public String sayHello(String name) {
return greeting.sayHello(name);
}
}
12
13. Field and Method Injection
public class CheckoutHandler {
@Inject @LoggedIn User user;
@Inject PaymentProcessor processor;
@Inject
void setShoppingCart(@Default Cart cart) {
…
}
}
13
14. Constructor Injection
public class CheckoutHandler {
@Inject
CheckoutHandler(@LoggedIn User user,
PaymentProcessor processor,
Cart cart) {
...
}
}
• Only one constructor can have @Inject
• Makes the bean immutable
14
15. Multiple Qualifiers and Qualifiers with Arguments
public class CheckoutHandler {
@Inject
CheckoutHandler(@LoggedIn User user,
@Reliable
@PayBy(CREDIT_CARD)
PaymentProcessor processor,
@Default Cart cart) {
...
}
}
15
16. Bean Initialization Sequence
1. Default bean constructor or the one annotated with @Inject
2. Values of all injected fields of the beans
3. All initializer methods of the beans
1.Defined within bean hierarchy
2. Call order not portable within a single bean
4. @PostConstruct method
16
17. Typesafe Resolution
• Resolution is performed at system initialization time
• @Qualifier, @Alternative
– Unsatisfied dependency
• Create a bean which implements the bean type with all qualifiers
• Explicitly enable an @Alternative bean using beans.xml
• Make sure it is in the classpath
– Ambiguous dependency
• Introduce a qualifier
• Disable one of the beans using @Alternative
• Move one implementation out of classpath
17
18. Client Proxies
• Container indirects all injected references through a proxy
object unless it is @Dependent
• Proxies may be shared between multiple injection points
@ApplicationScoped @RequestScoped
public class UserService { public class User {
private String message;
@Inject User user; // getter & setter
}
public void doSomething() {
user.setMessage("...");
// some other stuff
user.getMessage();
}
}
18
19. Scopes
• Beans can be declared in a scope
– Everywhere: @ApplicationScoped, @RequestScoped
– Web app: @SessionScoped (must be serializable)
– JSF app: @ConversationScoped
• Transient and long-running
– Pseudo-scope (default): @Dependent
– Custom scopes via @Scope
• Runtime makes sure the right bean is created at the right time
• Client do NOT have to be scope-aware
19
20. ConversationScope – Sample Code
• Like session-scope – spans multiple requests to the server
• Unlike – demarcated explicitly by the application, holds state
with a particular browser tab in a JSF application
public class ShoppingService {
@Inject Conversation conv;
public void startShopping() {
conv.begin();
}
. . .
public void checkOut() {
conv.end();
}
}
20
21. Custom Scopes – Sample Code
@ScopeType
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface ClusterScoped {}
public @interface TransactionScoped {}
public @interface ThreadScoped {}
21
22. @New Qualifier
• Allows to obtain a dependent object of a specified class,
independent of declared scope
– Useful with @Produces
@ConversationScoped
public class Calculator { . . . }
public class PaymentCalc {
@Inject Calculator calculator;
@Inject @New Calculator newCalculator;
}
22
23. Producer & Disposer
• Producer
– Exposes any non-bean class as a bean, e.g. a JPA entity
– Bridge the gap with Java EE DI
– Perform custom initialization not possible in a constructor
– Define multiple beans, with different scopes or initialization, for the
same implementation class
– Method or field
– Runtime polymorphism
• Disposer – cleans up the “produced” object
– e.g. explicitly closing JDBC connection
– Defined in the same class as the “producer” method
23
24. Producer – Sample Code
@SessionScoped
public class Preferences implements Serializable {
How often the method is called,
private PaymentStrategyType paymentStrategy;
Lifecycle of the objects returned
. . .
Default is @Dependent
@Produces @Preferred @SessionScoped
public PaymentStrategy getPaymentStrategy() {
switch (paymentStrategy) {
case CREDIT_CARD: return new CreditCardPaymentStrategy();
case CHECK: return new CheckPaymentStrategy();
case PAYPAL: return new PayPalPaymentStrategy();
default: return null;
}
}
}
@Inject @Preferred PaymentStrategy paymentStrategy;
24
26. Interceptors
• Two interception points on a target class
– Business method
– Lifecycle callback
• Cross-cutting concerns: logging, auditing, profiling
• Different from EJB 3.0 Interceptors
– Type-safe, Enablement/ordering via beans.xml, ...
• Defined using annotations and DD
• Class & Method Interceptors
– In the same transaction & security context
•
26
27. Interceptors – Business Method (Logging)
@InterceptorBinding @LoggingInterceptorBinding
public class MyManagedBean {
@Retention(RUNTIME) . . .
@Target({METHOD,TYPE}) }
public @interface LoggingInterceptorBinding {
}
@Interceptor
@LoggingInterceptorBinding
public class @LogInterceptor {
@AroundInvoke
public Object log(InvocationContext context) {
System.out.println(context.getMethod().getName());
System.out.println(context.getParameters());
return context.proceed();
}
}
27
28. Why Interceptor Bindings ?
• Remove dependency from the interceptor implementation class
• Can vary depending upon deployment environment
• Allows central ordering of interceptors
28
29. Interceptors – Business Method (Transaction)
@InterceptorBinding @Transactional
public class ShoppingCart { . . . }
@Retention(RUNTIME)
@Target({METHOD,TYPE})
public @interface Transactional { public class ShoppingCart {
} @Transactional public void checkOut() { . . . }
@Interceptor
@Transactional
public class @TransactionInterceptor {
@Resource UserTransaction tx;
@AroundInvoke
public Object manageTransaction(InvocationContext context) {
tx.begin()
context.proceed();
tx.commit();
}
}
http://blogs.sun.com/arungupta/entry/totd_151_transactional_interceptors_using
29
30. Decorators
• Complimentary to Interceptors
• Apply to beans of a particular bean type
– Semantic aware of the business method
– Implement “business concerns”
• Disabled by default, enabled in “beans.xml”
– May be enabled/disabled at deployment time
• @Delegate – injection point for the same type as the beans
they decorate
• Interceptors are called before decorators
30
31. Decorator – Sample Code
public interface Account { @Decorator
public BigDecimal getBalance(); public abstract class LargeTransactionDecorator
public User getOwner(); implements Account {
public void withdraw(BigDecimal amount);
public void deposit(BigDecimal amount); @Inject @Delegate @Any Account account;
} @PersistenceContext EntityManager em;
public void withdraw(BigDecimal amount) {
<beans ...
…
<decorators>
}
<class>
org.example.LargeTransactionDecorator public void deposit(BigDecimal amount);
</class> …
}
</decorators>
}
</beans>
31
32. Alternatives
• Deployment time polymorphism
• @Alternative beans are unavailable for injection, lookup or
EL resolution
– Bean specific to a client module or deployment scenario
• Need to be explicitly enabled in “beans.xml” using
<alternatives>/<class>
32
33. Events – More decoupling
• Annotation-based event model
– Based upon “Observer” pattern
• A “producer” bean fires an event
• An “observer” bean watches an event
• Events can have qualifiers
• Transactional event observers
– IN_PROGRESS, AFTER_SUCCESS, AFTER_FAILURE,
AFTER_COMPLETION, BEFORE_COMPLETION
33
35. Stereotypes
• Encapsulate architectural patterns or common metadata in a
central place
– Encapsulates properties of the role – scope, interceptor bindings,
qualifiers, etc.
• Pre-defined stereotypes - @Interceptor, @Decorator,
@Model
• “Stereotype stacking”
35
36. Stereotypes – Sample Code (Pre-defined)
@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Model {}
• Use @Model on JSF “backing beans”
36
37. Stereotypes – Sample Code (Make Your Own)
@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Named
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}
37
38. Loose Coupling
• Alternatives – deployment time polymorphism
• Producer – runtime polymorphism
• Interceptors – decouple technical and business concerns
• Decorators – decouple business concerns
• Event notifications – decouple event producer and
consumers
• Contextual lifecycle management decouples bean
lifecycles
38
39. Strong Typing
• No String-based identifiers, only type-safe Java constructs
– Dependencies, interceptors, decorators, event produced/consumed, ...
• IDEs can provide autocompletion, validation, and refactoring
• Lift the semantic level of code
– Make the code more understandable
– @Asynchronous instead of asyncPaymentProcessor
• Stereotypes
39
40. CDI & EJB - Typesafety
• Java EE resources injected using String-based names (non-
typesafe)
• JDBC/JMS resources, EJB references, Persistence
Context/Unit, …
• Typesafe dependency injection
• Loose coupling, Strong typing
• Lesser errors due to typos in String-based names
• Easier and better tooling
40
41. CDI & EJB – Stateful Components
• Stateful components passed by client in a scope
• Explicitly destroy components when the scope is complete
• Session bean through CDI is “contextual instance”
• CDI runtime creates the instance when needed by the client
• CDI runtime destroys the instance when the context ends
41
42. CDI & EJB – As JSF “backing bean”
•JSF managed beans used as “glue” to connect with Java EE enterprise
services
• EJB may be used as JSF managed beans
• No JSF backing beans “glue”
• Brings transactional support to web tier
42
43. CDI & EJB – Enhanced Interceptors
• Interceptors only defined for session beans or message
listener methods of MDBs
• Enabled statically using “ejb-jar.xml” or @Interceptors
• Typesafe Interceptor bindings on any managed bean
• Can be enabled or disabled at deployment using “beans.xml”
• Order of interceptors can be controlled using “beans.xml”
43
44. CDI & JSF
• Brings transactional support to web tier by allowing EJB as JSF
“backing beans”
• Built-in stereotypes for ease-of-development - @Model
• Integration with Unified Expression Language
– <h:dataTable value=#{cart.lineItems}” var=”item”>
• Context management complements JSF's component-oriented
model
44
45. CDI & JSF
• @ConversationScope holds state with a browser tab in JSF
application
– @Inject Conversation conv;
• Transient (default) and long-running conversations
• Shopping Cart example
• Transient converted to long-running: Conversation.begin/end
• @Named enables EL-friendly name
45
46. CDI & JPA
• Typesafe dependency injection of PersistenceContext &
PersistenceUnit using @Produces
– Single place to unify all component references
@PersistenceContext(unitName=”...”) EntityManager em;
@Produces @PersistenceContext(unitName=”...”)
CDI @CustomerDatabase EntityManager em;
Qualifier
@Inject @CustomerDatabase EntityManager em;
46
48. CDI & JAX-RS
• Manage the lifecycle of JAX-RS resource by CDI
– Annotate a JAX-RS resource with @RequestScoped
• @Path to convert class of a managed component into a
root resource class
48
49. CDI & JAX-WS
• Typesafe dependency injection of @WebServiceRef using
@Produces
@Produces
@WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;
@Inject PaymentService remotePaymentService;
• @Inject can be used in Web Service Endpoints & Handlers
• Scopes during Web service invocation
– RequestScope during request invocation
– ApplicationScope during any Web service invocation
49
50. Portable Extensions
• Key development around Java EE 6 “extensibility” theme
• Addition of beans, decorators, interceptors, contexts
– OSGi service into Java EE components
– Running CDI in Java SE environment
– TX and Persistence to non-EJB managed beans
• Integration with BPM engines
• Integration with 3 -party frameworks like Spring, Seam, Wicket
rd
• New technology based upon the CDI programming model
50
51. Portable Extension – How to author ?
• Implement javax.enterprise.inject.spi.Extension
SPI
– Register service provider
• Observe container lifecycle events
– Before/AfterBeanDiscovery, ProcessAnnotatedType
• Ways to integrate with container
– Provide beans, interceptors, or decorators
– Satisfy injection points with built-in or wrapped types
– Contribute a scope and context implementation
– Augment or override annotation metadata
51
52. Portable Extensions – Weld Bootstrapping in Java SE
public class HelloWorld {
public void printHello(@Observes ContainerInitialized event,
@Parameters List<String> parameters) {
System.out.println("Hello" + parameters.get(0));
}
}
52
53. Portable Extensions – Weld Logger
public class Checkout {
@Inject Logger log;
public void invoiceItems() {
ShoppingCart cart;
...
log.debug("Items invoiced for {}", cart);
}
}
53
54. Portable Extensions – Typesafe injection of OSGi Service
• org.glassfish.osgi-cdi – portable extensionin
GlassFish 3.1
• Intercepts deployment of hybrid applications
• Discover (using criteria), bind, track, inject the service
• Metadata – filter, wait timeouts, dynamic binding
http://blogs.sun.com/sivakumart/entry/typesafe_injection_of_dynamic_osgi
54
61. Summary
• Provides standards-based and typesafe dependency injection
in Java EE 6
• Integrates well with other Java EE 6 technologies
• Portable Extensions facilitate richer programming model
• Weld is the Reference Implementation
– Integrated in GlassFish and JBoss
• Improving support in IDEs
61