Spring 带有运行时参数的 IOC DI

Spring IOC DI with runtime parameters

我是 IOC 和 DI 的新手,所以我猜我在这里遗漏了一些高级设计原则,但我不知道如何让我的架构工作。

我有一个 REST API 端点,它接受两条 POST 数据:客户 ID 和类型 ID。其余 api 然后需要 return 一组特定 customer/type 组合的数据。

这是我正在做的事情的粗略描述:

控制器正在获取通过 post 数据传入的实体 ID,并通过 JPA 存储库为它们获取适当的实体。

然后我构造一个数据生成器对象(将实体作为构造函数参数),并使用它来处理 API.

的所有数据收集

问题: 因为数据生成器采用两个动态构造函数参数,所以它不能直接输入到控制器中,而必须使用 new .但是,在数据生成器内部,我需要访问 JPA 存储库。访问这些存储库的唯一方法是通过 DI。但是我不能 DI,因为对象是 new'ed 而不是由 IOC 容器 DI'。

有没有一种方法可以解决这个问题,这样我就不会遇到这个问题?我是否违反了有关 IOC 的一些规则?我在某处有错误的假设吗?任何建议表示赞赏。

谢谢!

编辑:数据生成器的伪代码

public class DataGenerator {
    private Customer customer;
    private Type type

    public DataGenerator(Customer customer, Type type) {
        this.cusomter = customer;
        this.type = type;
    }

    public generateData() {
        if(customer == x && type == y) {
            //JPA REPOSITORY QUERY
        } else {
            //DIFFERENT JPA REPOSITORY QUERY
        }
    }
}

我想你可能在这条线上的某个地方感到困惑。您应该有一个 Service 命中您的存储库,并将信息提供给控制器。一种粗略的设置是这样的。

@Controller 
public MyController {

    @AutoWired
    private DataService dataService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    private DataGenerator readBookmark(@PathVariable Long customerId, @PathVariable Integer typeId) {
        return dataService.getData(customerId, typeId);
    }
}

@Service
public class DataService {

    @AutoWired
    private JPARepository repository;

    public DataGenerator getData(long customerId, int typeId) {
        Type typeDetails = repository.getType(typeId);
        Customer customerDetails = repository.getCustomer(customerId);
        return new DataGenerator(customerDetails, typeDetails);
    }
}