gpt4 book ai didi

java - 如何 Autowiring transient 属性?

转载 作者:行者123 更新时间:2023-12-01 19:35:30 25 4
gpt4 key购买 nike

我有一个实体,例如 Employee,其中包含 @Transient 对象薪资,该薪资将从相关表/实体 DailyTimeRecord (DTR) 派生。 DTR 对象数据检索使用连接,并且也在 Employee 对象中 Autowiring 。 DTR对象列表将作为计算Salary对象值的基础。

我在这里找到[1]:Why is my Spring @Autowired field null?应避免使用new关键字,并让IoC容器创建对象。另外,我希望避免使用 new 关键字,以尽量减少代码的耦合性,并尽可能确保 future 的兼容性和支持可扩展性。因此,我有接口(interface) Salary 并由 SalaryImpl 类实现。

但是每次我尝试在 transient 属性 Salary 上运行 Autowiring 的代码时,它总是为空。我在这里找到了根本原因[2]:How to populate @Transient field in JPA?在 JPA 中 Transient 始终为 null。

如何创建一个在 transient 属性时避免使用 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);

}

薪资接口(interface)基础/实现类

   @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;
}
}

最佳答案

首先,@Transient 来自 JPA,与 Spring 无关。

其次,为了能够让Spring向Employee注入(inject)bean,Employee也需要注册为spring bean。但实际上,您可以认为 Employee 是由 JPA 实现在幕后使用“new”创建的。这就是为什么 spring 不能自动将其他 bean 连接到它。

如果您确实需要这样做,您可以使用 AspectJ 来按照 docs 中的描述进行操作。 .

我个人没有尝试这种方法,因为您可以简单地让您的 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, .... ,.....);
}

}

关于java - 如何 Autowiring transient 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57814892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com