在服务构建器*serviceImpl类中,@Reference注释提供一个空值,这里有一个陷阱。当impl类第一次激活(在@activate函数中)时,@reference注释工作。但是稍后,当我们在服务中调用一个方法时,@reference依赖项为null。
public interface Base{}
................
@component(service = Base.class)
public class Sample implements Base{}
..................
@Component(.......)
public class TestServiceImpl{
@Reference
private volatile Base b;
public void doSomething(){
b.test(); // null point exception
}
@Activate
@Modified
protected void activate(Map<String, Object> properties)
{
b.test(); // works here
}
}
}
// portlet class
@Component(
immediate = true,
property = {
"javax.portlet.name=" + somevalue,
"mvc.command.name=" + somename
},
service = MVCResourceCommand.class
)
public class TestCommand implements MVCResourceCommand{
@Override
public boolean serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws PortletException {
testService.doSomething();// throws NPE becoz Base b is null inside the method
}
....
@Reference
TestLocalService testService;
... }发布于 2022-02-28 09:30:27
注意:使用随机大写(@component)和方法上的@Component注释,您的代码有些奇怪。我假设这只是一个错误(虽然我不知道为什么您不只是复制/粘贴您的可疑代码到您的问题。
@Reference总是对容器管理的@Component进行解析。但是,您有可能自己创建其中一个对象--在这种情况下:
另一个可能的原因是您可能已经自己保存了一些@Component-annotated对象,并且它已经没有部署。您也不应该这样做,因为这可能意味着它的@Reference是无效/无效的。
https://stackoverflow.com/questions/71292671
复制相似问题