留言板

OSGi @Reference and @Component

Ketan Solanki,修改在6 年前。

OSGi @Reference and @Component

Junior Member 帖子: 63 加入日期: 14-5-28 最近的帖子
Hello,

I am struggling to get dependency injection in my project using these 2 annotations. I know there is already a thread going on here but that's still inconclusive and hasn't been resolved yet - so posting a new thread!

I have gone through this link as well and I have done my implementation according to that.

My component is below

@Component(
        immediate = true, property = {"search.engine.impl=LiferayElasticsearchCluster"},
        service = QuerySuggester.class, name = "bookmarkQuerySuggester"
)
public class BookmarkQuerySuggester extends BaseQuerySuggester {


in a module. This module has been started and is active when I check in gogo console. Hence the references are available inside Liferay.

But when I refer this in a Portlet class (which is also a @Component class and is in a different module - jar file too) somehow that portlet is NOT getting initialized. The strangest thing is, I don't get any logs or any reference of that particular portlet while DEBUG level logging is enabled.

@Reference
private BookmarkQuerySuggester bookmarkQuerySuggester;
I have tried with setter based injection too where I put a SOP to print something but nothing comes up in the logs!

I am stuck now, can someone please help me here? Thanks very much for your help,

Regards,
Ketan
thumbnail
David H Nebinger,修改在6 年前。

RE: OSGi @Reference and @Component (答复)

Liferay Legend 帖子: 14918 加入日期: 06-9-2 最近的帖子
Ketan Solanki:
But when I refer this in a Portlet class (which is also a @Component class and is in a different module - jar file too) somehow that portlet is NOT getting initialized. The strangest thing is, I don't get any logs or any reference of that particular portlet while DEBUG level logging is enabled.

@Reference
private BookmarkQuerySuggester bookmarkQuerySuggester;


Right, it won't start because there is no BookmarkQuerySuggester instance available for injection. This is absolutely correct.

But wait, you say, I have my @Component where I'm declaring my service:

@Component(
       immediate = true, property = {"search.engine.impl=LiferayElasticsearchCluster"},
       service = QuerySuggester.class, name = "bookmarkQuerySuggester"
)


Your service, the one that you're component implements, is simply QuerySuggester.

How do you fix this? Two choices:

  • Change the member to be a QuerySuggester class only, then perhaps add a target expression to @Reference to exclude inappropriate matches.
  • Change the @Component service to support two classes, both QuerySuggester and BookmarkQuerySuggester. By using both service classes, the @Reference would be satisfied.









Come meet me at Devcon 2017 or 2017 LSNA!