Java Reference
In-Depth Information
// Do something...
}
}
The @Instantiate annotation results in i POJO creating a component instance at exe-
cution time when the containing bundle is activated and the component becomes valid.
The main downside of this approach is that it hinders component reusability, because
it presupposes that the number and configuration of your component instances are the
same for every scenario in which they're used. This isn't typically the case.
Although the XML and annotation approaches likely satisfy the majority of use
cases for most people, they don't cover all possibilities. For example, what if you need
to dynamically create component instances? i POJO provides two different ways to
accomplish this.
FACTORY SERVICE INSTANCE CREATION
We've told you that i POJO maintains a strict separation between type and instance, but
we didn't tell you how i POJO does this. For each described component type, i POJO
registers an org.apache.felix.ipojo.Factory service in the OSG i service registry at
execution time. The Factory interface is fairly straightforward and largely defines
methods for creating configured component instances.
Internally, i POJO uses these factory services to create the component instances you
declare using XML or @Instantiate . To differentiate one component factory service
from another, i POJO registers them with unique factory.name service properties,
which is the name of the component class by default but can be any name you choose.
How does this allow you to dynamically create component instances? Because these
are just OSG i services, you can look them up in the service registry and use them like
any normal service. The following listing shows an example.
Listing 12.7 Creating components using the component factory service
@Component(immediate=true)
public class Creator {
@Requires(filter="(factory.name=hello)")
private Factory helloFactory;
Dependent on component
factory service
B
private Map<String, ComponentInstance> instances =
new HashMap<String, ComponentInstance>();
public void create(String name) {
Hashtable props = new Hashtable();
props.put("name", name);
ComponentInstance instance =
helloFactory.createComponentInstance(props);
instances.put(name, instance);
}
C
Creates
instance
public void rename(String oldName, String newName) {
ComponentInstance instance = instances.remove(oldName);
if (instance != null) {
Hashtable props = new Hashtable();
props.put("name", newName);
 
Search WWH ::




Custom Search