猿问

如何自动装配瞬态属性?

我有一个实体,例如 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;

          }

   }


绝地无双
浏览 160回答 2
2回答

梵蒂冈之花

首先,@Transient来自 JPA ,与 Spring 无关。其次,为了能够让Spring注入bean Employee,Employee还需要注册为spring bean。但实际上,您可以认为 Employee 是由 JPA 实现在幕后使用“new”创建的。这就是为什么 spring 不能自动将其他 bean 连接到它。如果您确实需要这样做,您可以AspectJ按照文档中的描述进行操作。我个人没有尝试这种方法,因为你可以简单地让你SalaryService接受Employee作为其参数之一来计算他的工资,这比该方法更简单且易于理解AspectJ。public interface SalaryService {&nbsp; &nbsp; public double computeSalary(Employee employee , List<Benefit> benefits, List<Deduction> deductions);}&nbsp;客户端代码如下所示:@Servicepublic class EmployeeService {&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private SalaryService salaryService;&nbsp; &nbsp; @Transactional&nbsp; &nbsp; public void computeEmployeeSalary(Integer employeeId){&nbsp; &nbsp; &nbsp; &nbsp; Employee employee = entityManager.find(Employee.class , employeeId);&nbsp; &nbsp; &nbsp; &nbsp; salaryService.computeSalary(employee, .... ,.....);&nbsp; &nbsp; }}

泛舟湖上清波郎朗

实体对象是由 JPA 实现(如 Hibernate)创建的,而不是由 spring 管理的。它们既不是单例也不是原型,所以一般来说,您不能在实体 bean 的属性上使用自动装配(因为自动装配只能在 spring bean 上完成)。
随时随地看视频慕课网APP

相关分类

Java
我要回答