亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何自動裝配瞬態屬性?

如何自動裝配瞬態屬性?

絕地無雙 2023-07-13 13:52:41
我有一個實體,例如 Employee,其中包含 @Transient 對象薪資,該薪資將從相關表/實體 DailyTimeRecord (DTR) 派生。DTR 對象數據檢索使用連接,并且也在 Employee 對象中自動裝配。DTR 對象列表將作為計算薪資對象值的基礎。new應避免使用using關鍵字,并讓IoC容器創建對象。另外,我希望避免使用new關鍵字,以盡量減少代碼的耦合性,并盡可能確保未來的兼容性和支持可擴展性。因此,我有接口 Salary 并由 SalaryImpl 類實現。但是每次我嘗試在瞬態屬性 Salary 上運行自動裝配的代碼時,它總是為空。我在這里找到了根本原因new當它是瞬態屬性時,我將如何創建一個避免使用關鍵字的對象?實體類? ?@Entity? ?Class Employee implements Serializable {? ? ? ? ? //Attributes from DB here? ? ? ? ? @OneToMany? ? ? ? ? @JoinColumn(name="empNumber", referencedColumnName = "empNumber")? ? ? ? ? private List<DTR> dtr;? ? ? ? ? @Autowired? ? ? ? ? @Transient? ? ? ? ? private Salary salary;? ? ? ? ? //getters ang setters here? ? ? ? ? public double computeSalary(){? ? ? ? ? }? ?}薪資接口? ?public interface Salary {? ? ? ? ? public double computeSalary(List<Benefit> benefits, List<Deduction> deductions);? ?}薪資接口基礎/實現類? ?@Service? ?public class SalaryImpl implements Salary, Serializable {? ? ? ? ? //other attributes here? ? ? ? ? //getter and setters? ? ? ? ? //other methods? ? ? ? ? @Override? ? ? ? ? public double computeSalary(List<Benefit> benefits, List<Deduction> deductions){? ? ? ? ? ? ? ? ?return 0;? ? ? ? ? }? ?}
查看完整描述

2 回答

?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

首先,@Transient來自 JPA ,與 Spring 無關。


其次,為了能夠讓Spring注入bean Employee,Employee還需要注冊為spring bean。但實際上,您可以認為 Employee 是由 JPA 實現在幕后使用“new”創建的。這就是為什么 spring 不能自動將其他 bean 連接到它。


如果您確實需要這樣做,您可以AspectJ按照文檔中的描述進行操作。


我個人沒有嘗試這種方法,因為你可以簡單地讓你SalaryService接受Employee作為其參數之一來計算他的工資,這比該方法更簡單且易于理解AspectJ。


public interface SalaryService {

    public double computeSalary(Employee employee , List<Benefit> benefits, List<Deduction> deductions);

客戶端代碼如下所示:


@Service

public class EmployeeService {


    @Autowired

    private SalaryService salaryService;


    @Transactional

    public void computeEmployeeSalary(Integer employeeId){

        Employee employee = entityManager.find(Employee.class , employeeId);

        salaryService.computeSalary(employee, .... ,.....);

    }


}


查看完整回答
反對 回復 2023-07-13
?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

實體對象是由 JPA 實現(如 Hibernate)創建的,而不是由 spring 管理的。

它們既不是單例也不是原型,所以一般來說,您不能在實體 bean 的屬性上使用自動裝配(因為自動裝配只能在 spring bean 上完成)。


查看完整回答
反對 回復 2023-07-13
  • 2 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號