[英]Access repository or service from entity
I'm using Spring Boot to write server application. 我正在使用Spring Boot编写服务器应用程序。
Most of the time, I write all business logic inside services, where I use @Autowired
to access repositories and other services. 大多数时候,我在服务内部编写所有业务逻辑,在这里我使用
@Autowired
访问存储库和其他服务。
However, sometimes I want to access certain service or property from @Entity
class, which cannot use @Autowired
. 但是,有时我想从
@Entity
类访问某些服务或属性,而不能使用@Autowired
。
For instance, I have an entity that should be able to serialize itself to JSON. 例如,我有一个实体,应该能够将自己序列化为JSON。 In JSON, it should have imageUrl field, which contains of image name (stored in database and as a property in the
@Entity
class) and base url, which is only available in application.properties. 在JSON中,它应该具有imageUrl字段,该字段包含图像名称(存储在数据库中,并作为
@Entity
类中的属性)和基本url,仅在application.properties中可用。 This means that I have to use @Value
annotation inside @Entity
class, but it doesn't work that way. 这意味着我必须在
@Entity
类中使用@Value
批注,但是那样行不通。
So I create a service which looks like this: 因此,我创建了一个看起来像这样的服务:
@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;
}
}
And then inside the @Entity
class I write the following code: 然后在
@Entity
类中,编写以下代码:
@JsonProperty
public String getImageUrl() {
return FilesService.getInstance().getFileUrl(imageName);
}
This works, but it doesn't look right. 这可行,但是看起来不正确。 Moreover, I concern whether this can lead to some side effects if used with less trivial
@Service
classes or @Repository
classes. 此外,我担心如果与较少的
@Service
类或@Repository
类一起使用,是否会导致某些副作用。
What is the correct way to use @Repository
and @Service
classes from @Entity
classes or any other non- @Component
classes (classes not managed by Spring)? 使用
@Entity
类或任何其他非@Component
类(不受Spring管理的类)中的@Repository
和@Service
类的正确方法是什么?
Well, I'd say there's no correct way of using repositories and services from entities since every fiber of my being screams of wrongness but that being said , you can refer to this link for suggestions on how to do it. 好吧,我会说没有正确的方法来使用实体的存储库和服务,因为我的每一个想法都在抱怨错误,但是,您可以参考此链接以获取有关如何做的建议。
In your case, I think it should allow you to populate @Value
fields within your entities, which would actually be preferable to autowiring the service. 就您而言,我认为它应该允许您在实体中填充
@Value
字段,这实际上比自动装配服务更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.