我为Dozer创建了一个instatiator bean(http://dozer.sourceforge.net/)。但是当我注入这个EJB时,它会抛出nullpointer异常。
这是我用于初学Dozer的Singleton启动Bean
package com.unijunction.ordercloud.common.rest;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import javax.ejb.Startup;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Startup
@Singleton
public class DozerInstantiator {
private DozerBeanMapper mapper;
private Logger log = LoggerFactory.getLogger(DozerInstantiator.class);
public enum States {
BEFORESTARTED, STARTED, PAUSED, SHUTTINGDOWN
};
private States state;
//TODO: DozerIsntantiator is retunring null
@PostConstruct
public void initialize() throws Throwable {
log.info("---------------Dozer Starting Up-----------------");
try{
state = States.BEFORESTARTED;
this.mapper = new DozerBeanMapper();
} catch (Throwable e) {
log.error("Cause: " + e.getCause());
log.error("Message: " + e.getMessage());
log.error("Class: " + e.getClass());
log.error("StackTrace: " + e.getStackTrace());
throw e;
}
state = States.STARTED;
log.info("---------------Dozer Started-----------------");
}
@PreDestroy
public void terminate() {
state = States.SHUTTINGDOWN;
// Perform termination
log.info("---------------Dozer Shuttingdown-----------------");
}
public States getState() {
return this.state;
}
public void setState(States state) {
this.state = state;
}
public DozerBeanMapper getMapper() {
return this.mapper;
}
}
它被注入的类是泛型类,如下所示:
public class DtoConverter<T1, T> {
protected final Class<T> entityClass;
@EJB
DozerInstantiator dozerInstantiator;
//instance for dozer to convert beans
protected DozerBeanMapper mapper;
private Logger log = LoggerFactory.getLogger(DozerInstantiator.class);
public DtoConverter(){
this.entityClass = null;
}
/**
* Setup the class
*
*/
public DtoConverter(Class<T> entityClass) {
this.entityClass = entityClass;
//TODO: only allow one instance of this to exist
//https://ordercloud.atlassian.net/browse/API-80
try{
mapper = dozerInstantiator.getMapper(); //<--- This throws null pointer
}catch(Exception e){
mapper = new DozerBeanMapper();
}
}
抛出空指针异常。我已经尝试将它用作Stateless和Statefull bean,但结果仍然相同。
任何帮助将不胜感激。这是在JBOSS AEP 6上运行的JAVA EE。
答案 0 :(得分:1)
事实证明,CDI规范不允许将单例注入到泛型类中。所以我写了一个静态的最终推土机实例的懒惰初始化。
我在DozerInstantiator中添加了以下两个方法:
public static DozerBeanMapper getInstance(){
return MapperHolder.instance;
}
private static class MapperHolder{
static final DozerBeanMapper instance = new DozerBeanMapper(mappingList);
}
然后在泛型类中调用它:
DozerInstantiator dozerInstantiator = new DozerInstantiator();
try{
mapper = dozerInstantiator.getInstance();
}catch(Exception e){
log.error("Failed to initialise singleton Dozer bean");
}
答案 1 :(得分:0)
Dozer API中包含单身人士/此方法应符合您的需求
Mapper getMapper() {
return DozerBeanMapperSingletonWrapper.getInstance();
}
如果要将其转换为CDI,请参阅@Produce注释规范。