问题
I have read here to use the optional resolution within the "Import-Package" directive carefully, but don't really understand why. Also what is the difference between optional and not specifying a dependency at all?
回答1:
If you fail to specify an Import-Package at all, then your bundle cannot access the package even if it available and exported by some other bundle.
If you import the package optionally, then your bundle can use it if available, but that package not being available does not prevent resolution of your bundle.
You should avoid optional dependencies at the package level. Either you depend on a package or you don't. Normally a need for optional dependencies indicates that your bundle has poor coherency, i.e. it's doing too many unrelated things within one module.
回答2:
If you say it is optional, than it might occur if it is exported from some other bundle. If you do not import it at all, it will be never available for the bundle. So, for what do you need it? If you really have an optional part in your bundle, you can import the optional dependencies. However, you have to check if they are there when you use it.
OSGi will not complain if an optional import can not be found, but the JVM will complain if you bundles uses something which is not imported at all.
来源:https://stackoverflow.com/questions/20352400/difference-between-import-package-resolution-optional-and-no-dependency-at-all