Ошибка при создании bean-компонента - Inject Configuration-Class в Service не работает - PullRequest
0 голосов
/ 25 октября 2019

Я пытаюсь внедрить REST-сервис, как в этом уроке: Урок

Но я получил эту ошибку:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageService' defined in file: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.airgnb.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.airgnb.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException

Класс обслуживания:

@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 FileStorageServiceException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }
}

Класс конфигурации:

@Configuration
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {

    private String uploadDir;

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }
}

Приложение также аннотировано так:

@SpringBootApplication
@EnableConfigurationProperties({FileStorageProperties.class})
public class TestApp implements InitializingBean {

Я думаю, единственное, что отличается, это то, что я использую приложение.yml вместо application.properties, но я определил свойства, подобные учебнику, но только в стиле yml.

Я понятия не имею, почему FileStorageProperties не вводится и, следовательно, FileStorageService не может быть создан.

Я уже пытался аннотировать приложение с помощью @Import(FileStoroageProperties.class), а также некоторыми другими способами внедрения зависимостей, такими как внедрение в поле.

1 Ответ

2 голосов
/ 25 октября 2019

Не думаю, что FileStorageProperties не вводили. Ошибка будет указывать, что Бин типа FileStorageProperties не был найден. У вас просто есть NullPointerException внутри конструктора.

Я думаю, fileStorageProperties.getUploadDir() вернул null.

Вы установили свойство file.uploadDir в application.yml или application.properties

...