1. 程式人生 > >OSGi bundle之間通過反射呼叫方法

OSGi bundle之間通過反射呼叫方法

兩個bundle之間不通過pom檔案引入jar包方式呼叫另一個方法,通過反射的方式呼叫。

前提:被呼叫的方法的bundle需要配置  <Export-Package> 要提供的被引用的包</Export-Package>

呼叫方需要配置 <Import-Package>引入的包名,多個可通過,隔開</Import-Package>

如此便可以通過java反射來呼叫另一個bundle中的方法。

示例export-package,import-package如何配置(通過pom檔案中配置bnd來實現):

<!-- 由BND來完成JAR包的OSGI化 -->
	<build>
		<resources>
			<resource>
				<filtering>true</filtering>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<!-- <version>${maven-bundle-plugin.version}</version> -->
				<version>3.5.0</version>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Bundle-Version>${project.version}</Bundle-Version>
						<Bundle-Activator>com.myDemo.test.Activator</Bundle-Activator>
						<Export-Package>com.myDemo.test*;version=${project.version}</Export-Package>
						<Embed-Dependency>*;scope=compile|runtime</Embed-Dependency>
						<Embed-Directory>target/dependency</Embed-Directory>
						<Embed-Transitive>true</Embed-Transitive>
					<Import-Package> 
							com.mydemo.user.service,
							org.osgi.framework,
							*;resolution:=optional
					</Import-Package>
					</instructions>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>${maven.resources.version}</version>
				<executions>
					<execution>
						<id>filter</id>
						<goals>
							<goal>resources</goal>
						</goals>
						<phase>generate-resources</phase>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>8</source>
					<target>8</target>
					<!-- <maxmem>256M</maxmem> -->
				</configuration>
			</plugin>

		</plugins>
	</build>

之後使用java反射即可,如同普通java程式中一樣。