我正在使用Spring Boot編寫服務器應用程序。來自實體的訪問存儲庫或服務
大多數情況下,我會在服務內寫入所有業務邏輯,其中我使用@Autowired
來訪問存儲庫和其他服務。
但是,有時我想訪問@Entity
類中的某些服務或屬性,該類不能使用@Autowired
。
例如,我有一個實體應該能夠將自己序列化爲JSON。在JSON中,它應該有imageUrl字段,其中包含圖像名稱(存儲在數據庫中,作爲@Entity
類中的一個屬性)和base 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
類。
什麼是使用@Repository
和@Service
類從@Entity
類或任何其它非@Component
類(而不是由Spring管理類)的正確方法?
你爲什麼不在該實體中存儲url?當客戶端/控制器創建新實體時,文件路徑可以傳遞給您的實體。我知道沒有設置規則「,但在您的實體中隱藏依賴關係'感覺'錯誤。 – Rabiees
那麼,ntot服務。編寫自定義編組器 – Sarief