Tapestry5使用带有构造函数args的Inject服务

时间:2012-08-19 01:36:58

标签: java spring tapestry

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

实施例

使用Tapestry Servce

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);
    }

}

1 个答案:

答案 0 :(得分:2)

假设@Inject与实例化类似,你并不完全正确。当您的服务使用@Scope(ScopeConstants.PERTHREAD)进行注释时,您可能会对此提出异议,但即便如此,tapestries IoC也会为您实例化服务。我发现我的大多数服务都只通过tapestry实例化了一次,@Inject它们给了我这个服务的参考。如果您想要@Inject服务,首先需要使用AppModule来定义它。通过IoC提供服务的最简单方法是在AppModule中将其绑定:

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

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

@Inject
private ServiceInterface service;

如果您的服务需要构造函数参数,则可以使用所需的参数在ServiceImplementation.class中创建构造函数。如果这些论点本身就是绑定服务,那么挂毯会解决这个问题并且你已经完成了。如果这些参数不是Tapetsry已知的服务,并且您无法出于任何原因绑定它们,则可以在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。它很好地概述了您可以使用的所有强大功能。

相关问题