2016-07-26 42 views
4

我正在使用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管理類)的正確方法?

+0

你爲什麼不在該實體中存儲url?當客戶端/控制器創建新實體時,文件路徑可以傳遞給您的實體。我知道沒有設置規則「,但在您的實體中隱藏依賴關係'感覺'錯誤。 – Rabiees

+1

那麼,ntot服務。編寫自定義編組器 – Sarief

回答

2

嗯,我會說沒有正確的方式使用存儲庫和實體的服務,因爲我的每一根纖維都是錯誤的尖叫聲,但是據說,你可以參考this link以獲得關於如何去做的建議。

就你而言,我認爲它應該允許你在實體中填充@Value字段,這實際上比自動裝配服務更可取。

相關問題