我正在尝试创建一个名为TaskBeanFactory的BeanFactory,我可以将其自动装入另一个在线程上运行的原型类。我想要一个由Factory返回的bean的不同实例,它基于我要传递给它的taskName但是当我启动应用程序时,我得到一个空指针异常,因为taskName为null。我查看了this article,但我对如何配置Factory然后传入taskName感到困惑。
工厂:
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
@Data
@Component
@NoArgsConstructor
public class TaskBeanFactory extends AbstractFactoryBean<GenericTask>{
private TaskNameEnum taskName;
public TaskBeanFactory(TaskNameEnum taskName) {
setSingleton(false);
}
@Override
public Class<?> getObjectType() {
return GenericTask.class;
}
@Override
protected GenericTask createInstance() throws Exception {
switch (taskName) {
case FILE_OPERATION:
return new FileTask();
case DATA_OPERATION:
return new DataTask();
default:
return new GenericTask();
}
}
}
工厂使用的类:
@Data
public class GenericTask {
private String idTask;
public void executeTask(Work work) {};
}
@Component
@Scope(value="prototype")
public class FileTask extends GenericTask {
@Override
public void executeTask(Work work) {
//some processing
}
}
@Component
@Scope(value="prototype")
public class DataTask extends GenericTask {
@Override
public void executeTask(Work work) {
//some processing
}
}
和调用Factory的线程:
@Slf4j
@Data
@Scope("prototype")
@Component
public class WorkerThread implements Runnable {
@Autowired
private TaskBeanFactory taskBeanFactory;
@Autowired
private DataService dataService;
@Override
public void run() {
//iterate a Map of taskIds from the dataService
taskBeanFactory.setTaskName(TaskNameEnum.valueOf(taskEntry.getKey()));
GenericTask genericTask = taskBeanFactory.getObject();
//expecting genericTask to be of Type FileTask if called with one Key
//or of Type DataTask if called with another
}
}
}