java—在运行时指定一些(但不是全部)构造函数参数

zdwk9cvp  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(306)

假设我定义了以下服务接口(以及实现):

interface Service1 { /* Methods omitted for brevity */ }
interface Service2 { /* Methods omitted for brevity */ }

我还有一个无法修改的接口(我无法控制):

interface YouAreNotAllowedToModifyMe {
  Object createSomething();
}

进一步假设我有一个实现 YouAreNotAllowedToModifyMe 接口并接受这些服务的实现以及当前 HttpServletRequest . 请注意,请求是一个实现细节,而不是接口的一部分。

class Demo implements YouAreNotAllowedToModifyMe {

  private final HttpServletRequest request;
  private final Service1 service1;
  private final Service2 service2;

  @Inject
  public Demo(HttpServletRequest request, Service1 service1, Service2 service2) {
    this.request = request;
    this.service1 = service1;
    this.service2 = service2;
  }

  public Object createSomething() {
    // Use the request, service1, and service2 in order to create the object.
  }
}
``` `Demo` 在运行时之前无法示例化,因为它需要当前 `HttpServletRequest` ,但是我希望cdi injection负责注入其他参数。我该怎么做?
基本上,我希望这是可能的(不是):

class Foo {

@Inject
private final Instance demoInstance;

public void doSomething(HttpServletRequest request) {

// This is pretend. This won't really work, though I wish it would.
// Essentially, I pass in the request and CDI takes care of everything else.
Demo demo = demoInstance.get(request);

}
}

sqxo8psd

sqxo8psd1#

不能将构造函数的一半参数注入,一半参数手工提供。但是,您有其他选择:
HttpServletRequest . 更好的是,使用三角洲钉。然后你就可以注射 HttpServletRequest !
修改 Demo 作为工厂的例子 YouAreNotAllowedToModifyMe ,而不是实施它:

@ApplicationScoped //probably-but not necessarily???
public class Demo {
    @Inject
    private final Service1 service1;
    @Inject
    private final Service2 service2;

    public YouAreNotAllowedToModifyMe makeYouAreNotAllowedToModifyMe(HttpServletRequest request) {
        return new YouAreNotAllowedToModifyMeImpl(request);
    }

    private class YouAreNotAllowedToModifyMeImpl implements YouAreNotAllowedToModifyMe {
        YouAreNotAllowedToModifyMeImpl(HttpServletRequest request) {
            // do what you must...
        }

        // implement it!
        // remember, you can actually use service1 &
        // service 2 from the enclosing instance
    }
}

相关问题