[英]Access repository or service from entity
我正在使用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
类或任何其他非@Component
类(不受Spring管理的类)中的@Repository
和@Service
类的正确方法是什么?
好吧,我会说没有正确的方法来使用实体的存储库和服务,因为我的每一个想法都在抱怨错误,但是,您可以参考此链接以获取有关如何做的建议。
就您而言,我认为它应该允许您在实体中填充@Value
字段,这实际上比自动装配服务更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.