如果用@Autowired注入(inject)的对象离开当前页面,有没有办法初始化它?
例如,如果当前用户在写入时上传照片,则照片信息将存储在注入(inject)对象中的 hashmap 中。
此时,如果用户上传图片并取消写入(移动到另一个页面),则必须初始化注入(inject)的对象。目前,如果取消写入并再次注册文本,则先前存储的图像仍保留在对象中。
这是我的代码
When a user registers a picture, the uploadImage receives the file as a parameter.
Controller .java
@PostMapping("/image")
public void uploadImage(@RequestPart MultipartFile upload) {
s3Service.tempUpload(upload);
}
Transfer the file to tempUpload of s3Service object and upload it to /temp of s3 After writing is complete, save the file in the Map variable of TempImage to move the photo to the actual folder.
服务.java
private TempImage tempImage;
@Autowired
public S3Service(TempImage tempImage) {
this.tempImage = tempImage;
}
public String tempUpload(MultipartFile file) {
s3Client.putObject(
new PutObjectRequest(bucket + "/temp", fileName)
);
tempImage.setTempFile(fileName, bytes);
}
TempImage.java
@Component
public class TempImage {
private final HashMap<String, byte[]> tempFile = new HashMap<>();
public HashMap<String, byte[]> getTempFile() {
return tempFile;
}
public void setTempFile(String fileName, byte[] bytes) {
this.tempFile.put(fileName, bytes);
}
public void clearTempFile() {
this.tempFile.clear();
}
}
此时,如果用户返回或离开页面,则应该初始化 TempImage 对象。
目前还在继续积累。
最佳答案
有几个 spring bean 范围。
singleton
Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
Spring 默认将 bean 创建为单例。
但是,springboot/spring 无法理解用户是否离开或进入页面,因为它不受它们控制。您可以创建另一个服务,通过在用户离开页面时调用 api 来清除 TempImage 中的所有数据。
关于java - 离开特定页面时初始化bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62441379/