我正在使用 Spring Boot 编写服务器应用程序。
大多数时候,我在服务中编写所有业务逻辑,我在其中使用 @Autowired
访问存储库和其他服务。
但是,有时我想从 @Entity
类访问某些服务或属性,而不能使用 @Autowired
。
例如,我有一个应该能够将自身序列化为 JSON 的实体。在 JSON 中,它应该有 imageUrl 字段,其中包含图像名称(存储在数据库中并作为 @Entity
类中的属性)和基本 url,仅在 application.properties 中可用。这意味着我必须在 @Entity
类中使用 @Value
注释,但它不能那样工作。
所以我创建了一个如下所示的服务:
@Service
public class FilesService {
private static FilesService instance;
@PostConstruct
public void init() {
FilesService.instance = this;
}
public static FilesService getInstance() {
return instance;
}
@Value("${files.path}")
String filesPath;
@Value("${files.url}")
String filesUrl;
public String saveFile(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
return null;
}
String filename = UUID.randomUUID().toString();
file.transferTo(new File(filesPath + filename));
return filename;
}
public String getFileUrl(String filename) {
if (filename == null || filename.length() == 0) {
return null;
}
return filesUrl + filename;
}
}
然后在 @Entity
类中,我编写了以下代码:
@JsonProperty
public String getImageUrl() {
return FilesService.getInstance().getFileUrl(imageName);
}
这行得通,但看起来不对。此外,我担心如果与不那么琐碎的 @Service
类或 @Repository
类一起使用,这是否会导致一些副作用。
使用 @Entity
类或任何其他非 @ 类的
类(非Spring管理的类)?@Repository
和 @Service
类的正确方法是什么组件
最佳答案
嗯,我想说没有正确的方法来使用来自实体的存储库和服务,因为我的每根纤维都在尖叫错误,但话虽如此,你可以引用 this link有关如何做的建议。
在您的情况下,我认为它应该允许您在实体中填充 @Value
字段,这实际上比 Autowiring 服务更可取。
关于java - 从实体访问存储库或服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593375/