为了账号安全,请及时绑定邮箱和手机立即绑定

如何自动装配瞬态属性?

如何自动装配瞬态属性?

绝地无双 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 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信