gpt4 book ai didi

java - Tapestry5 使用带有构造函数参数的注入(inject)服务

转载 作者:行者123 更新时间:2023-12-02 07:37:17 25 4
gpt4 key购买 nike

我是 Tapestry5 用户,想知道如何使用一些参数 @Inject 服务类。根据我的理解,使用 @Inject 注入(inject)服务类与使用 new MyClass(); 实例化类非常相似。我似乎遇到的问题是我不确定如何将参数传递到服务中。

示例

使用 Tapestry 服务

public class Main {

@Inject
private MyService myService;

public Main() {
//Where would I pass in my arguements?
this.myService();

//I can't seem to do this by passing the arg's in through
//this.myService(arg1, arg2) unless I may be missing something.
}

}

传统用法

public class Main {

public Main() {
//In this example I can pass my arg's into the constructor.
MyService myService = new MyService(arg1, arg2);
}

}

最佳答案

您认为 @Inject 与实例化类似的假设不太正确。当您的服务带有 @Scope(ScopeConstants.PERTHREAD) 注释时,您可能会对此有所争论。但即便如此,tapestries IoC将为您实例化该服务。我发现我的大多数服务仅由 Tapestry 实例化一次,并且 @Inject 它们为我提供了对此服务的引用。如果你想 @Inject 一个服务,你首先需要使用 AppModule 来定义它。 。通过 IoC 使服务可用的最简单方法是在 AppModule 中像这样绑定(bind)它:

public static void bind(ServiceBinder binder) {
binder.bind(ServiceInterface.class, ServiceImplementation.class)
}

然后在您的页面/组件中,您可以@Inject界面,例如:

@Inject
private ServiceInterface service;

如果您的服务需要构造函数参数,您可以在 ServiceImplementation.class 中创建一个构造函数来获取所需的参数。如果这些参数本身就是绑定(bind)服务,Tapestry 会解决这个问题,然后你就完成了。如果这些参数不是 Tapetsry 已知的服务,并且您出于某种原因无法绑定(bind)它们,则可以在 AppModule 中创建一个构建方法:

/**
* These methods may in them selves take bound services as arguments helping you build your new service
*/
public ServiceInterface buildServiceInterface(AnotherBoundService service2) {
...
return new ServiceImplementation(service2, someMoreArgsIfRequired)
}

也许您不想使用 IoC,您始终可以在页面/组件中实例化服务,因为它们只是简单的 pojo。请查看 IoC documentation 。它很好地概述了您可以使用的所有强大功能。

关于java - Tapestry5 使用带有构造函数参数的注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com