Mai*_*sad 13 java spring bean-validation spring-boot spring-restcontroller
这是我的FileStorageProperties
课:
@Data
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
private String uploadDir;
}
Run Code Online (Sandbox Code Playgroud)
这让我说:未通过 @enableconfigurationproperties 注册或标记为 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我错误提示:无法自动装配没有找到类型的 bean。
这是我的项目结构:
当我尝试运行它时,它给了我:
应用程序无法启动
描述:
com.mua.cse616.Service.FileStorageService 中构造函数的参数 0 需要一个无法找到的“com.mua.cse616.Property.FileStorageProperties”类型的 bean。
注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true)
行动:
考虑在您的配置中定义一个“com.mua.cse616.Property.FileStorageProperties”类型的 bean。
我该如何解决这个问题?
Pra*_*ant 28
这是预期的,因为@ConfigurationProperties
不会使类成为 Spring Component
。用 标记班级,@Component
它应该可以工作。请注意,一个类只能在它是Component
.
编辑:从 Spring 2.2+(参考)开始
@ConfigurationProperties
扫描注释的类@ConfigurationProperties
现在可以通过类路径扫描找到,作为使用@EnableConfigurationProperties
或的替代方法@Component
。添加@ConfigurationPropertiesScan
到您的应用程序以启用扫描。
归档时间: |
|
查看次数: |
13268 次 |
最近记录: |