JPA + Spring - 并行类层次结构

时间:2015-03-13 15:23:59

标签: java spring generics jpa spring-4

据我所知,在JPA实体上实现并行类层次结构的唯一方法如下:

@Entity
public abstract class Job<A extends Account> {

  @Any(metaColumn = @Column)
  @AnyMetaDef(
        idType = "integer",
        metaType = "string",
        metaValues = {
            @MetaValue(value = "AccountX", targetEntity = AccountX.class),
            @MetaValue(value = "AccountY", targetEntity = AccountY.class)
  })
  @ManyToOne @JoinColumn 
  private A account;

  public A getAccount() { return account; }
  public void setAccount(A account) { this.account = account; }
}

@Entity
public class JobX extends Job<AccountX> {}

@Entity
public class JobY extends Job<AccountY> {}

并行实体的位置如下:

@Entity
public abstract class Account {}

@Entity
public AcountX extends Account {}

@Entity
public AccountY extends Account {}

这实际上有效。 JobX类型的对象仅与AccountX类型的对象相关联。 这种设计背后的想法是最终能够根据类型呈现两种行为。 现在问题是Spring无法自动装配一个特定的bean提供两个实现。让我们更具体一点:

@Component
public class AccountService<A extends Account> {
    public A getAccount() { // gets the account }
}

public interface JobService<A extends Account, J extends Job<A>> {
    J saveJob(J job);
}

@Component
public class JobServiceX implements JobService<AccountX, JobX>  {

    @Autowired private AccountService<AccountX> accountService;

    @Override
    public JobX saveJob(JobX job) { // save implementation for JobX }
}

@Component
public class JobServiceY implements JobService<AccountY, JobY>  {

    @Autowired private AccountService<AccountY> accountService;

    @Override
    public JobY saveJob(JobY job) { // save implementation for JobY }
}

现在,如果我尝试使用泛型来实现特定类型的bean以定义行为:

@Component
public class JobHandler<A extends Account, J extends Job<A>> {
    @Autowired private JobService<A,J> jobService;
}

我收到以下错误:Could not autowire field: private JobService JobHandler.jobService; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [JobService] is defined: expected single matching bean but found 2: jobXService,jobYService

所以,我有两个问题:

  1. 有解决方法吗?我知道Spring 4处理泛型bean,这与使用JobService注释@Component相同,这显然是错误的,因为它是一个接口而不是实现。
  2. 无论上面的第1点如何,这都开始创建一个“泛型地狱”,因为现在我需要开始使我的所有Spring bean都是通用的。是否有更好的设计或更好的方法来做到这一点?有没有办法来使Job更通用,而是提供一个可以在子实体中覆盖的getter / setter?
  3. 提前感谢你们!

0 个答案:

没有答案