从实体访问存储库或服务

Ale*_*xey 6 java spring spring-boot

我正在使用 Spring Boot 编写服务器应用程序。

大多数情况下,我在服务中编写所有业务逻辑,@Autowired用于访问存储库和其他服务。

但是,有时我想从@Entity类访问某些服务或属性,而不能使用@Autowired.

例如,我有一个应该能够将自身序列化为 JSON 的实体。在 JSON 中,它应该有 imageUrl 字段,其中包含图像名称(存储在数据库中并作为@Entity类中的属性)和基本 url,仅在 application.properties 中可用。这意味着我必须@Value@Entity类中使用注释,但它不能那样工作。

所以我创建了一个看起来像这样的服务:

@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;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在@Entity类里面我写了下面的代码:

@JsonProperty
public String getImageUrl() {
    return FilesService.getInstance().getFileUrl(imageName);
}
Run Code Online (Sandbox Code Playgroud)

这有效,但看起来不对。此外,我担心如果与不太重要的@Service类或@Repository类一起使用,这是否会导致一些副作用。

什么是正确的使用方法@Repository,并@Service从班@Entity班或任何其它非@Component类(而不是由Spring管理类)?

Mil*_*vić 3

好吧,我想说没有正确的方法来使用来自实体的存储库和服务,因为我的每一根纤维都在尖叫着错误,但话虽这么说,您可以参考此链接以获取有关如何执行此操作的建议。

就您而言,我认为它应该允许您填充@Value实体中的字段,这实际上比自动装配服务更好。