我有一个SpringBoot应用程序,它通过@RestController公开了一个简单的RESTapi。它进行文件上传,并尝试从上传的excel文件中读取值。
问题在于;状态";的某个组件似乎不会在新请求时重置,就像这是某种并发问题一样。。我好像想不通。就像当我在第一个请求之后发出新的后续请求时,上一个请求的值仍然挂在ImportProcessor和后续对象中,它没有被重置,我不知道为什么。。
应用程序的服务层@Autowires a";ImportProcessor";组件,该组件有许多通过其方法修改的字段。示例:
@Component
@NoArgsConstructor
@Slf4j
public class ImportProcessor {
public static STATE processState = STATE.READY;
@Autowired
RegulativImporter regulativImporter;
@Autowired
DatabaseImporter databaseImporter;
Sheet strekning;
Sheet strekning_periode;
HashMap<Long, TakstkategoriEntity> successfulTakstkategori;
HashMap<Long, RegulativEntity> successfulRegulativ;
HashMap<Long, TakstEntity> successfulTakst;
public ImportJobInfo handleStartProcessingRequest(Workbook workbook) throws FailedToStartProcessingException {
if (processState == STATE.READY) {
setProcessState(STATE.IMPORTING);
ImportJobInfo importJobInfo = startProcessing(workbook);
cleanUpState();
return importJobInfo;
} else {
throw new FailedToStartProcessingException("Failed to start processing because of insufficient state:",
processState);
}
}
// Methods that modify and set these objects.. Changes state based on action, initialize hashMaps..
// Method that inserts part of the Hashmaps to a database using DatabaseImporter
}
这是呼叫服务:
@Service
@Slf4j
public class FergeregisterImportServiceImpl implements FergeregisterImportService {
@Autowired
ImportProcessor importProcessor;
@Override
public ImportJobInfo startImportJob(MultipartFile file) throws FailedToStartProcessingException {
InputStream excelInputStream;
Workbook workbook;
ImportJobInfo importJobInfo = null;
try {
excelInputStream = file.getInputStream();
workbook = new XSSFWorkbook(excelInputStream);
log.info("Successfully converted Excel inputstream to Apache-POI workbook.");
} catch (IOException e) {
log.error(e.getMessage() + " | cause: " + e.getCause());
throw new FailedToStartProcessingException("Failed to convert Excel inputstream to Apache-POI workbook.",
STATE.FAILED);
}
try {
importJobInfo = importProcessor.handleStartProcessingRequest(workbook);
} catch (FailedToStartProcessingException e) {
log.error(e.getMessage(), importProcessor.getProcessState());
throw e;
}
return importJobInfo;
}
// Some other methods..
}
如果我不@Autowire的ImportProcessor,它工作得很好,我没有并发问题。但是ImportService似乎完全不可能调用@Autowired DatabaseImporter,它是CrudRepository接口
如果我能确保ImportProcessor对每个新请求都有一个新的开始,那么一切都会按预期进行。我真的希望我能在这里得到一些提示。非常感谢。
Spring Boot基于Singleton模型,如果您没有指定bean作用域,这意味着当您@Autowired时指定为bean的每个组件(@component、@Service或其他任何组件(,无论在哪里,它都将始终是同一个实例,这就是为什么您的状态不会重置的原因。
希望这有助于回答你的问题。