java - 离开特定页面时初始化bean

标签 java spring spring-boot

如果用@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/

相关文章:

java - 数据库中的外键始终为空

java - 身份验证过滤器不适用于 Spring Boot

java - 如何将 jar 文件添加到项目而不是添加到 Tomcat lib 文件夹?

java - 如何刷新jMonkey中的所有输入事件

java - 在phpbb3中获取form_token和time_creation

java - 如何将@Before/@BeforeClass 与@Autowired 字段一起使用

java - Spring Batch 与 HazelCast 集成

java - 如何在 Spring MVC 2.5 项目中使用 MockMvc?

java - Hibernate\JPA 在高并发 Web 应用程序上的使用

java - 如何跳过 block 中的任何错误并继续下一个 block 项目?