Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Using a factory method to create POJO object

By default, iPOJO calls the POJO constructor to create objects. This constructor can either has no argument or receive the bundle context. However sometimes, you may want a more advanced object creation policy.

iPOJO allows you describing a factory method called to create POJO objects instead of the constructor. So, every time that iPOJO needs to create an instance of your POJO class, this method will be called to obtain the object.

To use this feature you need to add the factory-method attribute in the Component element as illustrated below:


<component
	className="org.apache.felix.ipojo.test.scenarios.component.FooProvider"
        factory-method="createProvider"
>
	...
</component>
{code}

The specified method must be a *static* method of the implementation class returning an *instance of this implementation class*. The following code shows an example of usage:

{code
}
    public static FooProvider createProvider() {
        if (singleton == null) {
            singleton = new FooProvider();
        }
        return singleton;
    }
{code}

This method must then call any valid constructor (potentially private) of the implementation class.
 

However, be aware that if you create an instance by using a {{factory-method}}, the called constructor hasn't access to values injected by the iPOJO container. So, the called constructor must not try accessing to services, properties... These objects will be accessible when the constructor returns.


As for "normal" constructor, the method-factory can receive the bundle context in argument, such as in:

{code
}
    public static FooProvider createProvider (BundleContext bc) {
        if (singleton == null) {
            singleton = new FooProvider(bc);
        }
        return singleton;
    }
FELIX
{code
include:apache-felix-ipojo-
menuFELIX:apache-felix-ipojo-menu
footer}
Wiki Markup
{include:apache-felix-ipojo-header}
{html}
<div class="content">
{html}
h1. Using a factory method to create POJO object

_By default, iPOJO calls the POJO constructor to create objects. This constructor can either has no argument or receive the bundle context. However sometimes, you may want a more advanced object creation policy._

iPOJO allows you describing a factory method called to create POJO objects instead of the  constructor. So, every time that iPOJO needs to create an instance of your POJO class, this method will be called to obtain the object.

To use this feature you need to add the {{factory-method}} attribute in the Component element as illustrated below:
{code:xml}
Section
Column
width80%
Code Block
xmlxml
Column
width20%
Include Page