1

您如何在guice中执行以下操作?

XmlSerializer一个依赖于接口的类XmlFormatterXmlFormatter:CompactXmlFormatter和.有 2 种实现PrettyXmlFormatter

另一个类MyApplication依赖于 2 个实例XmlSerializer。一个实例应配置为 aCompactXmlFormatter和另一个PrettyXmlFormatter

public class XmlSerializer {
    public XmlSerializer(XmlFormatter formatter) {
       ...
    }
}

public interface XmlFormatter {
    ...
}

public class CompactXmlFormatter implements XmlFormatter {
    ...
}

public class PrettyXmlFormatter implements XmlFormatter {
    ...
}

public class MyApplication {
    public MyApplication(XmlSerializer compactSerializer, XmlSerializer prettySerializer) {
        ...
    }
}

你如何构建这样的图表?

我知道,一旦你有了 2 个XmlSerializer实例,将它们注入到构造函数MyApplication的参数中需要注释。MyApplication

我对你如何XmlFormatter同时绑定CompactXmlFormatter和更感兴趣PrettyXmlFormatter

4

1 回答 1

0

使用绑定注释来区分每个XmlFormatter.

在你的Module

bind(XmlFormatter.class).aannotatedWith(Pretty.class)
    .to(PrettyXmlFormatter.class);
bind(XmlFormatter.class).aannotatedWith(Compact.class)
    .to(CompactXmlFormatter.class);

和:

@Inject public MyApplication(
    @Compact XmlSerializer compactSerializer, 
    @Pretty XmlSerializer prettySerializer) {
    ...

当然,您必须定义@Pretty@Compact注释:

@BindingAnnotation 
@Target({ FIELD, PARAMETER, METHOD }) 
@Retention(RUNTIME) 
public @interface Pretty {}

@BindingAnnotation 
@Target({ FIELD, PARAMETER, METHOD }) 
@Retention(RUNTIME) 
public @interface Compact {}
于 2011-10-27T08:01:04.617 回答