[英]Spring @Inject service class return null pointer exception
I have a Converter
class where I have used the following so that I can use @Inject
to access my service class. 我有一个Converter
类,在其中使用了以下内容,以便可以使用@Inject
访问我的服务类。
@Named("myMB")
@ViewAccessScoped
However when I tried to use 但是当我尝试使用
myservice.getCategories();
I am getting null pointer exception
at this line. 我在这一行收到null pointer exception
。 What could be the reason for this? 这可能是什么原因? I have used the same service method in ManagedBean
to populate selectOneMenu
, but when used in Converter class, gives me exception. 我在ManagedBean
使用了相同的服务方法来填充selectOneMenu
,但是在Converter类中使用时,却给了我异常。
Converter class 转换器类
@FacesConverter("categoryConverter")
@Named("myMB")
@ViewAccessScoped
public class CategoryConverter implements Converter {
@Inject
CategoryService myservice;
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
System.out.println("reached in converter "+value);
try {
List<Category> cat = myservice.getCategories();
for (Category cat : category) {
if (cat.getCategoryCode() == value) {
return cat;
}
}
}
} catch (Exception e) {
System.out.println("exception from getAsObject ");
e.printStackTrace();
}
return null;
}
That can happen if you used it as @FacesConverter
instance instead of as @Named
instance. 如果将其用作@FacesConverter
实例而不是@Named
实例, @FacesConverter
发生这种情况。 The @Inject
doesn't work on @FacesConverter
. @Inject
在@FacesConverter
上@FacesConverter
。 Get rid of @FacesConverter
to avoid future confusion and reference the converter as converter="#{categoryConverter}"
(which uses @Named
) instead of as converter="categoryConverter"
(which uses @FacesConverter
). 摆脱@FacesConverter
以避免将来的混乱,并以converter="#{categoryConverter}"
(使用@Named
)而不是converter="categoryConverter"
(使用@FacesConverter
)来引用该转换converter="#{categoryConverter}"
。
Note that I assume that the Spring part is properly configured, otherwise it would be still null
. 请注意,我假设已正确配置Spring部分,否则它将仍然为null
。 I don't do Spring, so I can't tell form top of head if it works inside a CDI managed bean instead of a Spring managed bean. 我不做Spring,所以我不能告诉表单的顶部是否在CDI托管bean而不是Spring托管bean中工作。 I find it only surprising and amusing that you're mixing CDI and Spring, while Spring is intented as competitor/alternative to CDI/EJB. 我发现将CDI和Spring混合使用,而Spring却是CDI / EJB的竞争者/替代者,这让我感到惊讶和可笑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.