我有一個可能或可能返回null的可注入提供程序。當它爲空時我收到一個異常。我註冊提供程序作爲一個單身人士,我可以註冊它作爲一種SingletonContext,我自定義爲supportsNullCreation()返回true?我想如果我可以做到這一點,即使findOrCreate()返回null,我的代碼仍然會運行,這是我想要的。如何在Jersey中使用supportsNullCreation()?
@ApplicationPath("rest")
public class MyApplication extends ResourceConfig
{
public MyApplication()
{
...
// Provider of DB
this.register(new AbstractBinder()
{
@Override
public void configure()
{
bindFactory(DbManager.class).to(EntityManagerFactory.class).in(Singleton.class);
}
});
}
然後這樣使用:
@Singleton
@Path("myservice")
public class WebServiceClass
{
// NOTE: Right now I have to comment this to run without a DB
@Inject
private EntityManagerFactory entityManagerFactory = null;
...
我得到的例外是這個...
java.lang.IllegalStateException: Context
[email protected] findOrCreate returned a null for
descriptor SystemDescriptor(
implementation=com.db.DbManager
contracts={javax.persistence.EntityManagerFactory}
scope=javax.inject.Singleton
qualifiers={}
descriptorType=PROVIDE_METHOD
descriptorVisibility=NORMAL
metadata=
rank=0
[email protected]f2b1
proxiable=null
proxyForSameScope=null
analysisName=null
id=145
locatorId=0
identityHashCode=863132354
reified=true)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2075)
...
非常感謝!這完全解決了問題,並且設計也更好。 – Coder1224