programing

스프링 부트에서 @ConfigurationProperties를 자동 연결할 수 없습니다.

madecode 2023. 2. 27. 22:09
반응형

스프링 부트에서 @ConfigurationProperties를 자동 연결할 수 없습니다.

여기 제 것이 있습니다.FileStorageProperties클래스:

 @Data
 @ConfigurationProperties(prefix = "file")
 public class FileStorageProperties {
       private String uploadDir;
 }

@enable configuration properties를 통해 등록되지 않았거나 spring 컴포넌트로 마킹되지 않았음을 알 수 있습니다.

그리고 여기 내 것이 있다.FileStorageService:

@Service
public class FileStorageService {

private final Path fileStorageLocation;

@Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) {
    this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
            .toAbsolutePath().normalize();

    try {
        Files.createDirectories(this.fileStorageLocation);
    } catch (Exception ex) {
        throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
    }
}

public String storeFile(MultipartFile file) {
    // Normalize file name
    String fileName = StringUtils.cleanPath(file.getOriginalFilename());

    try {
        // Check if the file's name contains invalid characters
        if(fileName.contains("..")) {
            throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
        }

        // Copy file to the target location (Replacing existing file with the same name)
        Path targetLocation = this.fileStorageLocation.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
    }
}

public Resource loadFileAsResource(String fileName) {
    try {
        Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
        Resource resource = new UrlResource(filePath.toUri());
        if(resource.exists()) {
            return resource;
        } else {
            throw new MyFileNotFoundException("File not found " + fileName);
        }
    } catch (MalformedURLException ex) {
        throw new MyFileNotFoundException("File not found " + fileName, ex);
    }
}
}

로 인해 : cannot autowire no bean type found 라고 하는 에러가 표시됩니다.

프로젝트 구조는 다음과 같습니다.

스프링 부트에서는 @ConfigurationProperties를 자동 연결할 수 없습니다.프로젝트 구조

실행하려고 하면 다음과 같은 결과가 나옵니다.


응용 프로그램 부팅 실패

설명:

com.mua.cse616 컨스트럭터의 파라미터 0.서비스.FileStorageService에는 'com.mua.cse616' 유형의 빈이 필요합니다.소유물.FileStorageProperties'를 찾을 수 없습니다.

주입 지점에는 - @org.springframework 주석이 있습니다.콩.공장.배송.자동배선(필수=true)

액션:

com.mua.cse616 유형의 빈을 정의하는 것을 검토합니다.소유물.[ File Storage Properties ]를 클릭합니다.


어떻게 하면 해결할 수 있을까요?

이것은 로서 기대되고 있다.@ConfigurationProperties클래스는 스프링이 되지 않습니다.Component. 클래스 마크하기@Component효과가 있을 거야클래스가 삽입될 수 있는 것은, 다음의 경우에 한정됩니다.Component.

편집: Spring 2.2+부터 (참조)@ConfigurationProperties검색 클래스 주석 포함@ConfigurationProperties이제 를 사용하는 대신 클래스 경로 스캔을 통해 찾을 수 있습니다.@EnableConfigurationProperties또는@Component. 어플리케이션에 추가하여 스캔을 활성화합니다.

주석 달기@ConfigurationProperties그리고.@Component

여기에서는 스프링 부트 @ConfigurationProperties외부화된 구성에 대한 주석입니다.속성 파일에서 클래스로 속성 값을 삽입하려고 할 수 있습니다.@ConfigurationProperties같은 고정관념의 주석을 가진 클래스 레벨에서@Component또는 추가@ConfigurationProperties에 대해서@Bean방법.

FileStorageProperties 클래스에 아래 주석을 추가합니다.

@Component

언급URL : https://stackoverflow.com/questions/57950383/spring-boot-cant-autowire-configurationproperties

반응형