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

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

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

  1. interface Service1 { /* Methods omitted for brevity */ }
  2. interface Service2 { /* Methods omitted for brevity */ }

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

  1. interface YouAreNotAllowedToModifyMe {
  2. Object createSomething();
  3. }

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

  1. class Demo implements YouAreNotAllowedToModifyMe {
  2. private final HttpServletRequest request;
  3. private final Service1 service1;
  4. private final Service2 service2;
  5. @Inject
  6. public Demo(HttpServletRequest request, Service1 service1, Service2 service2) {
  7. this.request = request;
  8. this.service1 = service1;
  9. this.service2 = service2;
  10. }
  11. public Object createSomething() {
  12. // Use the request, service1, and service2 in order to create the object.
  13. }
  14. }
  15. ``` `Demo` 在运行时之前无法示例化,因为它需要当前 `HttpServletRequest` ,但是我希望cdi injection负责注入其他参数。我该怎么做?
  16. 基本上,我希望这是可能的(不是):

class Foo {

@Inject
private final Instance demoInstance;

public void doSomething(HttpServletRequest request) {

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

}
}

sqxo8psd

sqxo8psd1#

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

  1. @ApplicationScoped //probably-but not necessarily???
  2. public class Demo {
  3. @Inject
  4. private final Service1 service1;
  5. @Inject
  6. private final Service2 service2;
  7. public YouAreNotAllowedToModifyMe makeYouAreNotAllowedToModifyMe(HttpServletRequest request) {
  8. return new YouAreNotAllowedToModifyMeImpl(request);
  9. }
  10. private class YouAreNotAllowedToModifyMeImpl implements YouAreNotAllowedToModifyMe {
  11. YouAreNotAllowedToModifyMeImpl(HttpServletRequest request) {
  12. // do what you must...
  13. }
  14. // implement it!
  15. // remember, you can actually use service1 &
  16. // service 2 from the enclosing instance
  17. }
  18. }
展开查看全部

相关问题