【问题标题】:Access repository or service from entity从实体访问存储库或服务
【发布时间】:2016-11-30 07:23:40
【问题描述】:

我正在使用 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 类的正确方法是什么?

【问题讨论】:

  • 你为什么不把 url 也存储在那个实体中呢?当客户端/控制器创建新实体时,可以将文件路径传递给您的实体。我知道没有固定的规则”,但在您的实体中拥有这种隐藏的依赖关系“感觉”是错误的。
  • 好吧,不服务。编写自定义编组器

标签: java spring spring-boot


【解决方案1】:

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

在您的情况下,我认为它应该允许您在实体中填充 @Value 字段,这实际上比自动装配服务更可取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2011-09-28
    • 2010-10-24
    • 2013-02-22
    • 2018-02-15
    • 2011-11-10
    • 1970-01-01
    相关资源
    最近更新 更多