假设我定义了以下服务接口(以及实现):
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);
}
}
1条答案
按热度按时间sqxo8psd1#
不能将构造函数的一半参数注入,一半参数手工提供。但是,您有其他选择:
为
HttpServletRequest
. 更好的是,使用三角洲钉。然后你就可以注射HttpServletRequest
!修改
Demo
作为工厂的例子YouAreNotAllowedToModifyMe
,而不是实施它: