Any bean in a Spring DM application context can easily get a reference to its bundle context by implementing the BundleContextAware interface (located in the org.springframework.osgi.context
package). When instantiating the bean, the Spring DM application context implementation detects that it implements this special interface and automatically hands the bundle context to the bean by calling the sole method of the interface, setBundleContext .
1. 自动注入BundleContext
public class OsgiAddict implements BundleContextAware {
public void setBundleContext(BundleContext bundleContext) {
...
}
}
<bean id="osgiAddict" class="com.manning.sdmia.ch04.OsgiAddict" />
2. Setter注入BundleContext
public class PojoOsgiAddict {
private BundleContext bundleContext;
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
<bean id="pojoOsgiAddict" class="com.manning.sdmia.ch04.PojoOsgiAddict">
<property name="bundleContext" ref="bundleContext" />
</bean>
3. Interact declaratively with bundles
The Spring DM osgi namespace comes with a bundle element that makes it possible to get
references to OSGi bundles and even manipulate them. By using the bundle element in an
application context, you define an org.osgi.framework.Bundle bean in it. For example:
<osgi:bundle id="springDmExtenderBundle" symbolic-
name="org.springframework.osgi.extender" />
<osgi:bundle id="myBundle" location="file:/my/bundle/repo/somebundle.jar" action="start" />
Attributes of the bundle element:
(1)
Attribute name:id
Values:Any XML-valid ID
Description:Unique ID of the bean in the application context.
(2)
Attribute name:symbolic-name
Values:Any valid OSGi symbolic-name
Description:The symbolic name of an already installed bundle
(3)
Attribute name:location
Values:Spring resource syntax
Description:The location to load the bundle from, usually to interact with and call some lifecycle
methods.
(4)
Attribute name:start-level
Values:Integer
Description:The bundle start level.
(5)
Attribute name:action
Values:install, start, update, stop, uninstall
Description: An action executed on the bundle. This uses the same semantics as the methods
from the Bundle interface, with preconditions weakened.
(6)
Attribute name:
Values:install, start, update,stop, uninstall
Description:An action executed on the bundle when the application context is destroyed. This uses
the same semantics as the methods from the Bundle interface, with preconditions weakened.