簡體   English   中英

使用 @RequestPart 注釋方法調用 rest API 時,所有注入的 Rest Controller 成員 bean 都為 NULL

[英]All injected member bean of Rest Controller are NULL when invoking a rest API with @RequestPart annotated method

下面是我的休息控制器代碼:

package com.tripura.fileserver.controller;

import com.magic.fileserver.annotation.TrackTime;
import com.magic.fileserver.model.ResponseMessage;
import com.magic.fileserver.service.S3Factory;
import com.magic.fileserver.service.SequenceGeneratorService;
import com.magic.fileserver.service.StorageService;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping(FileServerController.ROOT_MAPPING)
public class FileServerController {
    public static final String ROOT_MAPPING = "/api/fileserver";

    private final SequenceGeneratorService sequenceGeneratorService;
    private final StorageService storageService;
    private final S3Factory s3Factory;

    public FileServerController(SequenceGeneratorService sequenceGeneratorService, StorageService storageService, S3Factory s3Factory) {
        this.sequenceGeneratorService = sequenceGeneratorService;
        this.storageService = storageService;
        this.s3Factory = s3Factory;
    }

    @GetMapping(value = "/health/admin")
    @PreAuthorize("hasRole('ADMIN')")
    @TrackTime
    public ResponseEntity<?> checkRequestAdmin() {
        return new ResponseEntity<>("Hello admin", HttpStatus.OK);
    }
    @PostMapping(value = "/add/file", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    @PreAuthorize("hasRole('USER') or hasRole('CONSULTANT') or hasRole('ADMIN')")
    @TrackTime
    private ResponseEntity<ResponseMessage<String>> uploadFile(
            @RequestPart("files") List<MultipartFile> files) {
//        this.storageService.storeFileOnS3Bucket(files.get(0), image, fileName,
//                userName, category);
        ResponseMessage<String> responseMessage = new ResponseMessage<>();
        responseMessage.setMessage("File added: " + files.get(0).getOriginalFilename());

        return new ResponseEntity<>(responseMessage, HttpStatus.OK);
    }

問題是當我通過 POSTMAN 調用它時,如下所示:

    curl --location --request POST 'http://localhost:8096/api/fileserver/add/file' --form 'files=@"/G:/My Drive/Money_receipt.jpg"'

我可以看到有效的文件正在進入該方法,但所有注入的 bean在錯誤方法中都是 NULL 調試

我的環境:Java 17 (zulu17.28.13-ca-jdk17.0.0-win_x64) Spring Boot:2.6.7

最后我找到了解決方案。 這是一個愚蠢的錯誤,因為我將 API 方法uploadFile的訪問修飾符聲明為私有,如下所示:

private ResponseEntity<ResponseMessage<String>> uploadFile

將訪問修飾符更改為public后,問題已解決:

public ResponseEntity<ResponseMessage<String>> uploadFile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM