SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Constructor Injection and other new
features in Declarative Services 1.4
BJ Hargrave, IBM
a Component
Impl
a Service Impl
Service
Component
Runtime Impl
a Servicea Component
Instance
Component
Description
a Component
Confguration
registered service
tracks
dependencies
declarescomponent
createdby
controls 0..n
0..n
0..n
references
1..n
1
Configuration
Admin
0..n
1
0..n
1
1
<<service>>
Service Component
Runtime
Declarative Services
• A declarative model for publishing and
consuming OSGi services

• Introduced in Release 4 in 2005, it greatly
simplified programming OSGi services

• DS 1.1 added minor enhancements

• DS 1.2 added build-time annotations

• DS 1.3 added field injection, component
property types and introspection

• Service Component Runtime, SCR, is the
runtime which implements the spec and
manages the service components
>900 projects
>590 DS Components
https://openliberty.io/
Service Component
• A Java class which can optionally be registered as a service and can optionally
use services
• Described by XML in the bundle which is processed at runtime by SCR
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
name="example.provider.ExampleImpl" activate="activate">
<implementation class="example.provider.ExampleImpl"/>
<service>
<provide interface="example.api.Example"/>
</service>
<reference name="Log" interface="org.osgi.service.log.LogService" bind="setLog"/>
</scr:component>
Service Component using annotations
• But writing XML is for computers
• So DS supports for programming
with annotations
• Tools, like , process the
annotations at build-time into the
XML used by SCR at runtime
@Component
public class ExampleImpl implements Example {
private Map<String, Object> properties;
private LogService log;
@Activate
void activate(Map<String, Object> map) {
properties = map;
}
@Override
public boolean say(String message) {
log.log((int) properties.get("loglevel"), message);
return false;
}
@Reference
void setLog(LogService log) {
this.log = log;
}
}
Service Component using annotations
• @Component declares a service
component and any service it may
provide
• @Activate declares the activate
method which is called to complete
activation of the component
• @Reference declares a service
references by the component and can
be applied to a bind method (method
injection) or a field (field injection)
@Component
public class ExampleImpl implements Example {
private Map<String, Object> properties;
private LogService log;
@Activate
void activate(Map<String, Object> map) {
properties = map;
}
@Override
public boolean say(String message) {
log.log((int) properties.get("loglevel"), message);
return false;
}
@Reference
void setLog(LogService log) {
this.log = log;
}
}
So what is new in Declarative Services 1.4?
• Constructor Injection
• Activation fields
• Component Property Types enhancements
• Use to annotate components
• Name mapping enhancements: single-element annotations and PREFIX_
• Predefined component property types
• Component factory properties
• OSGi Logger support
Constructor Injection
Injection
• Method injection
• Field injection
• Constructor injection
@Reference
void setExample(Example example) {
this.example = example;
}
@Reference
private Example example;
private final Example example;
@Activate
public ExampleImpl(@Reference Example example) {
this.example = example;
}
Constructor Injection
• Static policy only!
• Scalar cardinality
• Multiple cardinality
• Service type from
generic signature
private final Example example;
@Activate
public ExampleImpl(@Reference Example example) {
this.example = example;
}
private final List<Example> examples;
@Activate
public ExampleImpl(@Reference List<Example> examples) {
this.examples = examples;
}
Constructor Injection
• Can also inject parameters
of types related to services
• Service type from
generic signature
@Activate
public ExampleImpl(
@Reference
ServiceReference<Example> sr,
@Reference
ComponentServiceObjects<Example> so,
@Reference(service=Example.class)
Map<String,Object> serviceProps,
@Reference
Map.Entry<Map<String,Object>,Example> tuple)
{ … }
Constructor Injection
• Can also inject activation
objects
• Parameters not
annotated @Reference
public @interface Props {
int my_port() default 8080;
}
@Activate
public ExampleImpl(
ComponentContext context,
BundleContext bc,
Map<String,Object> componentProps,
Props props) { … }
Activation Fields
Activation Fields
• Activation objects can now
also be injected in fields in
addition to being
parameters to the activate
method or the constructor
@Activate
private ComponentContext context;
@Activate
private BundleContext bc;
@Activate
private Map<String,Object> componentProps;
@Activate
private Props props;
Component Property Type
enhancements
Component Property Types
• Define and use your component properties in a type safe manner using
annotations
public @interface Props {
int my_port() default 8080; // my.port property
}
@Component
public class ExampleImpl implements Example {
private final int my_port;
@Activate
public ExampleImpl(Props props) {
my_port = props.my_port();
}
}
Component Property Types
• But if you want to specify a different value for your component, you need to
use a String
• Make sure to get property name and type right
public @interface Props {
int my_port() default 8080; // my.port property
}
@Component(property = {"my.port:Integer=9080"})
public class ExampleImpl implements Example {
…
}
Component Property Types
• Now you can use the component property type to annotate the component
and specify property values for your component in a type safe manner
@ComponentPropertyType
public @interface Props {
int my_port() default 8080; // my.port property
}
@Component
@Props(my_port=9080)
public class ExampleImpl implements Example {
…
}
Single-element Annotation
• A single-element annotation is an annotation which has one element named
value and all other elements, if any, have default values
• Property name for value element is derived from type name rather than
method name
@ComponentPropertyType
public @interface MyPort {
int value() default 8080; // my.port property
}
@Component
@MyPort(9080)
public class ExampleImpl implements Example {
…
}
Common prefix for property names
• Value of PREFIX_ field, whose value is a compile-time constant String, is
prefixed to property name
• Useful when property names have a common prefix to keep annotation
element names short
@ComponentPropertyType
public @interface ServerPort {
String PREFIX_ = "com.acme.";
int value() default 8080; // com.acme.server.port property
}
Predefined Component Property Types
• OSGi specifications will define Component Property Types for specified properties
• Common service properties: @ServiceRanking, @ServiceDescription
• HttpWhiteboard service properties: @HttpWhiteboardServletName,
@HttpWhiteboardServletPattern
• JAX-RS service properties: @JaxrsName, @JaxrsResource
@ComponentPropertyType
public @interface JaxrsName {
String PREFIX_ = "osgi.";
String value(); // osgi.jaxrs.name property
}
Component Factory Properties
Component Factory Properties
• Component Factory services only had two properties: component.name and
component.factory
@Component(factory="widget.factory")
public class WidgetImpl implements Widget { … }
@Component
public class WidgetUser {
@Reference(target="(component.factory=widget.factory)")
private ComponentFactory<Widget> factory;
@Activate
void activate() {
ComponentInstance<Widget> widget =
factory.newInstance(null);
}
}
Component Factory Properties
• Component Factory Properties are added to allow more decoration of the
factory
@Component(factory="widget.factory",
factoryProperty={"widget.quality=AAA"})
public class WidgetAAAImpl implements Widget { … }
@Component(factory="widget.factory",
factoryProperty={"widget.quality=B"})
public class WidgetBImpl implements Widget { … }
@Component
public class WidgetUser {
@Reference(target=
"(&(component.factory=widget.factory)(widget.quality=AAA))")
private ComponentFactory<Widget> factory;
}
OSGi Logger Support
OSGi Logger Support
• R7 includes a big update to the OSGi Log Service
• LoggerFactory which makes Loggers
• Like slf4j
• DS will support creating and injecting a Logger for the component implementation class
@Component
public class ExampleImpl implements Example {
@Reference(service=LoggerFactory.class)
// LoggerFactory.getLogger(ExampleImpl.class)
private Logger logger;
@Activate
void activate() { logger.info("initialized"); }
}
And a number of other small
improvements
Park City, UT
Constructor injection and other new features for Declarative Services 1.4

Weitere ähnliche Inhalte

Was ist angesagt?

Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
bwullems
 
D2 8 Enhydra Shark
D2 8   Enhydra SharkD2 8   Enhydra Shark
D2 8 Enhydra Shark
brutkowski
 
3 know more_about_rational_performance_tester_8-1-snehamoy_k
3 know more_about_rational_performance_tester_8-1-snehamoy_k3 know more_about_rational_performance_tester_8-1-snehamoy_k
3 know more_about_rational_performance_tester_8-1-snehamoy_k
IBM
 

Was ist angesagt? (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
GraphQL 101
GraphQL 101GraphQL 101
GraphQL 101
 
Visual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 OverviewVisual Studio 2010 and .NET 4.0 Overview
Visual Studio 2010 and .NET 4.0 Overview
 
Mike Taulty MIX10 Silverlight Frameworks and Patterns
Mike Taulty MIX10 Silverlight Frameworks and PatternsMike Taulty MIX10 Silverlight Frameworks and Patterns
Mike Taulty MIX10 Silverlight Frameworks and Patterns
 
Azure Function Workflow
Azure Function WorkflowAzure Function Workflow
Azure Function Workflow
 
Intel open mp
Intel open mpIntel open mp
Intel open mp
 
Spring core
Spring coreSpring core
Spring core
 
Oro Workflows
Oro WorkflowsOro Workflows
Oro Workflows
 
D2 8 Enhydra Shark
D2 8   Enhydra SharkD2 8   Enhydra Shark
D2 8 Enhydra Shark
 
Crafting high quality code
Crafting high quality code Crafting high quality code
Crafting high quality code
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Rmi
RmiRmi
Rmi
 
Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019Angular - Improve Runtime performance 2019
Angular - Improve Runtime performance 2019
 
Wwf
WwfWwf
Wwf
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
3 know more_about_rational_performance_tester_8-1-snehamoy_k
3 know more_about_rational_performance_tester_8-1-snehamoy_k3 know more_about_rational_performance_tester_8-1-snehamoy_k
3 know more_about_rational_performance_tester_8-1-snehamoy_k
 
Building modular enterprise scale angular js applications
Building modular enterprise scale angular js applicationsBuilding modular enterprise scale angular js applications
Building modular enterprise scale angular js applications
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
QTP Automation Testing Tutorial 3
QTP Automation Testing Tutorial 3QTP Automation Testing Tutorial 3
QTP Automation Testing Tutorial 3
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 

Ähnlich wie Constructor injection and other new features for Declarative Services 1.4

iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
mfrancis
 
Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)
LearningTech
 
API First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipelineAPI First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipeline
Pronovix
 

Ähnlich wie Constructor injection and other new features for Declarative Services 1.4 (20)

Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
It depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or notIt depends: Loving .NET Core dependency injection or not
It depends: Loving .NET Core dependency injection or not
 
OSGi compendium
OSGi compendiumOSGi compendium
OSGi compendium
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi style
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic Apps
 
Angular IO
Angular IOAngular IO
Angular IO
 
Azure Functions - Introduction
Azure Functions - IntroductionAzure Functions - Introduction
Azure Functions - Introduction
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
FOSDEM19 MySQL Component Infrastructure
FOSDEM19 MySQL Component InfrastructureFOSDEM19 MySQL Component Infrastructure
FOSDEM19 MySQL Component Infrastructure
 
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010
 
Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)
 
API First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipelineAPI First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipeline
 
PuppetConf 2017: Unlocking Azure with Puppet Enterprise- Keiran Sweet, Source...
PuppetConf 2017: Unlocking Azure with Puppet Enterprise- Keiran Sweet, Source...PuppetConf 2017: Unlocking Azure with Puppet Enterprise- Keiran Sweet, Source...
PuppetConf 2017: Unlocking Azure with Puppet Enterprise- Keiran Sweet, Source...
 
ASP.NET MVC 3
ASP.NET MVC 3ASP.NET MVC 3
ASP.NET MVC 3
 
Moduarlity patterns with OSGi
Moduarlity patterns with OSGiModuarlity patterns with OSGi
Moduarlity patterns with OSGi
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 

Mehr von bjhargrave

Mehr von bjhargrave (6)

The new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4JThe new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4J
 
OSGi and Java 9+
OSGi and Java 9+OSGi and Java 9+
OSGi and Java 9+
 
Services-First Migration to OSGi
Services-First Migration to OSGiServices-First Migration to OSGi
Services-First Migration to OSGi
 
Why OSGi?
Why OSGi?Why OSGi?
Why OSGi?
 
OSGi Puzzlers
OSGi PuzzlersOSGi Puzzlers
OSGi Puzzlers
 
OSGi 4.3 Technical Update: What's New?
OSGi 4.3 Technical Update: What's New?OSGi 4.3 Technical Update: What's New?
OSGi 4.3 Technical Update: What's New?
 

Kürzlich hochgeladen

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Kürzlich hochgeladen (20)

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Constructor injection and other new features for Declarative Services 1.4

  • 1. Constructor Injection and other new features in Declarative Services 1.4 BJ Hargrave, IBM
  • 2. a Component Impl a Service Impl Service Component Runtime Impl a Servicea Component Instance Component Description a Component Confguration registered service tracks dependencies declarescomponent createdby controls 0..n 0..n 0..n references 1..n 1 Configuration Admin 0..n 1 0..n 1 1 <<service>> Service Component Runtime Declarative Services • A declarative model for publishing and consuming OSGi services • Introduced in Release 4 in 2005, it greatly simplified programming OSGi services • DS 1.1 added minor enhancements • DS 1.2 added build-time annotations • DS 1.3 added field injection, component property types and introspection • Service Component Runtime, SCR, is the runtime which implements the spec and manages the service components >900 projects >590 DS Components https://openliberty.io/
  • 3. Service Component • A Java class which can optionally be registered as a service and can optionally use services • Described by XML in the bundle which is processed at runtime by SCR <?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="example.provider.ExampleImpl" activate="activate"> <implementation class="example.provider.ExampleImpl"/> <service> <provide interface="example.api.Example"/> </service> <reference name="Log" interface="org.osgi.service.log.LogService" bind="setLog"/> </scr:component>
  • 4. Service Component using annotations • But writing XML is for computers • So DS supports for programming with annotations • Tools, like , process the annotations at build-time into the XML used by SCR at runtime @Component public class ExampleImpl implements Example { private Map<String, Object> properties; private LogService log; @Activate void activate(Map<String, Object> map) { properties = map; } @Override public boolean say(String message) { log.log((int) properties.get("loglevel"), message); return false; } @Reference void setLog(LogService log) { this.log = log; } }
  • 5. Service Component using annotations • @Component declares a service component and any service it may provide • @Activate declares the activate method which is called to complete activation of the component • @Reference declares a service references by the component and can be applied to a bind method (method injection) or a field (field injection) @Component public class ExampleImpl implements Example { private Map<String, Object> properties; private LogService log; @Activate void activate(Map<String, Object> map) { properties = map; } @Override public boolean say(String message) { log.log((int) properties.get("loglevel"), message); return false; } @Reference void setLog(LogService log) { this.log = log; } }
  • 6. So what is new in Declarative Services 1.4? • Constructor Injection • Activation fields • Component Property Types enhancements • Use to annotate components • Name mapping enhancements: single-element annotations and PREFIX_ • Predefined component property types • Component factory properties • OSGi Logger support
  • 8. Injection • Method injection • Field injection • Constructor injection @Reference void setExample(Example example) { this.example = example; } @Reference private Example example; private final Example example; @Activate public ExampleImpl(@Reference Example example) { this.example = example; }
  • 9. Constructor Injection • Static policy only! • Scalar cardinality • Multiple cardinality • Service type from generic signature private final Example example; @Activate public ExampleImpl(@Reference Example example) { this.example = example; } private final List<Example> examples; @Activate public ExampleImpl(@Reference List<Example> examples) { this.examples = examples; }
  • 10. Constructor Injection • Can also inject parameters of types related to services • Service type from generic signature @Activate public ExampleImpl( @Reference ServiceReference<Example> sr, @Reference ComponentServiceObjects<Example> so, @Reference(service=Example.class) Map<String,Object> serviceProps, @Reference Map.Entry<Map<String,Object>,Example> tuple) { … }
  • 11. Constructor Injection • Can also inject activation objects • Parameters not annotated @Reference public @interface Props { int my_port() default 8080; } @Activate public ExampleImpl( ComponentContext context, BundleContext bc, Map<String,Object> componentProps, Props props) { … }
  • 13. Activation Fields • Activation objects can now also be injected in fields in addition to being parameters to the activate method or the constructor @Activate private ComponentContext context; @Activate private BundleContext bc; @Activate private Map<String,Object> componentProps; @Activate private Props props;
  • 15. Component Property Types • Define and use your component properties in a type safe manner using annotations public @interface Props { int my_port() default 8080; // my.port property } @Component public class ExampleImpl implements Example { private final int my_port; @Activate public ExampleImpl(Props props) { my_port = props.my_port(); } }
  • 16. Component Property Types • But if you want to specify a different value for your component, you need to use a String • Make sure to get property name and type right public @interface Props { int my_port() default 8080; // my.port property } @Component(property = {"my.port:Integer=9080"}) public class ExampleImpl implements Example { … }
  • 17. Component Property Types • Now you can use the component property type to annotate the component and specify property values for your component in a type safe manner @ComponentPropertyType public @interface Props { int my_port() default 8080; // my.port property } @Component @Props(my_port=9080) public class ExampleImpl implements Example { … }
  • 18. Single-element Annotation • A single-element annotation is an annotation which has one element named value and all other elements, if any, have default values • Property name for value element is derived from type name rather than method name @ComponentPropertyType public @interface MyPort { int value() default 8080; // my.port property } @Component @MyPort(9080) public class ExampleImpl implements Example { … }
  • 19. Common prefix for property names • Value of PREFIX_ field, whose value is a compile-time constant String, is prefixed to property name • Useful when property names have a common prefix to keep annotation element names short @ComponentPropertyType public @interface ServerPort { String PREFIX_ = "com.acme."; int value() default 8080; // com.acme.server.port property }
  • 20. Predefined Component Property Types • OSGi specifications will define Component Property Types for specified properties • Common service properties: @ServiceRanking, @ServiceDescription • HttpWhiteboard service properties: @HttpWhiteboardServletName, @HttpWhiteboardServletPattern • JAX-RS service properties: @JaxrsName, @JaxrsResource @ComponentPropertyType public @interface JaxrsName { String PREFIX_ = "osgi."; String value(); // osgi.jaxrs.name property }
  • 22. Component Factory Properties • Component Factory services only had two properties: component.name and component.factory @Component(factory="widget.factory") public class WidgetImpl implements Widget { … } @Component public class WidgetUser { @Reference(target="(component.factory=widget.factory)") private ComponentFactory<Widget> factory; @Activate void activate() { ComponentInstance<Widget> widget = factory.newInstance(null); } }
  • 23. Component Factory Properties • Component Factory Properties are added to allow more decoration of the factory @Component(factory="widget.factory", factoryProperty={"widget.quality=AAA"}) public class WidgetAAAImpl implements Widget { … } @Component(factory="widget.factory", factoryProperty={"widget.quality=B"}) public class WidgetBImpl implements Widget { … } @Component public class WidgetUser { @Reference(target= "(&(component.factory=widget.factory)(widget.quality=AAA))") private ComponentFactory<Widget> factory; }
  • 25. OSGi Logger Support • R7 includes a big update to the OSGi Log Service • LoggerFactory which makes Loggers • Like slf4j • DS will support creating and injecting a Logger for the component implementation class @Component public class ExampleImpl implements Example { @Reference(service=LoggerFactory.class) // LoggerFactory.getLogger(ExampleImpl.class) private Logger logger; @Activate void activate() { logger.info("initialized"); } }
  • 26. And a number of other small improvements Park City, UT