这是我的
FileStorageProperties
课程:
@Data
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
private String uploadDir;
}
这让我说:未通过@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);
}
}
}
这给了我错误:无法自动装配未找到类型的bean。
这是我的项目结构:
当我尝试运行它时,它给了我:
应用程序无法启动
描述:
com.mua.cse616.Service.FileStorageService 中构造函数的参数 0 需要类型为“com.mua.cse616.Property.FileStorageProperties”的 bean,但无法找到。
注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(必需= true)
行动:
考虑在配置中定义“com.mua.cse616.Property.FileStorageProperties”类型的 bean。
我该如何解决这个问题?
这是预期的,因为
@ConfigurationProperties
不会使类成为 Spring Component
。用 @Component
标记该类,它应该可以工作。请注意,只有当类是 Component
时才能注入。
编辑:从 Spring 2.2+(参考)
@ConfigurationProperties
扫描
现在可以通过类路径扫描找到用 @ConfigurationProperties
注解的类,作为使用 @EnableConfigurationProperties
或 @Component
的替代方法。 将 @ConfigurationPropertiesScan
添加到您的应用程序以启用扫描。
尝试使用
@ConfigurationProperties
和 @Component
进行注释
在这里,Spring Boot
@ConfigurationProperties
是外部化配置的注释。如果您尝试将属性值从属性文件注入到类中,您可以在类级别添加@ConfigurationProperties
,并使用构造型注释,例如@Component
或将 @ConfigurationProperties
添加到 @Bean
方法。
以我为例 我有
@ConfigurationProperties("limits-service")
在我的课上但错过了
@ConfigurationPropertiesScan
在主应用程序类中 LimitsServiceApplication
将
@ConfigurationPropertiesScan
添加到 LimitsServiceApplication
有效。
在 FileStorageProperties 类中添加以下注释:
@Component
您的主课程缺少
@EnableConfigurationProperties(FileStorageProperties.class);