繁体   English   中英

根据实现中使用的泛型使用接口的一个实现(应用类型)

[英]Use one implementation of an interface depending on used generic in implementation (applied type)

我有两个接口。 一个接口包含信息,第二个接口应该使用第一个接口。 第二个接口有一个通用必须是第一个接口的实现。

我想根据我收到的第一个接口的实现自动使用第二个接口的实现。

让我展示一下界面。 (我更改了域并简化了它,但是你得到了基本的想法。)

//This contains information needed to publish some information
//elsewhere, on a specific channel (MQ, Facebook, and so on)
public interface PubInfo {

    String getUserName();
    String getPassword();
    String getUrl();

    Map<String, String> getPublishingSettings();
} 



//Implementation of this interface should be for one implementation 
//PubInfo
public interface Publisher<T extends PubInfo> {
    void publish(T pubInfo, String message);
}

让我们假设我有这些PubInfo的实现...

public class FacebookPubInfo implements PubInfo {
    // ...
}

public class TwitterPubInfo implements PubInfo {
    // ...
}

......以及Publisher的这些

@Component
public class FacebookPublisher implements Publisher<FacebookPubInfo> {

    @Override
    public void publish(FacebookPubInfo pubInfo, String message) {
        // ... do something
    }
}

@Component
public class TwitterPublisher implements Publisher<TwitterPubInfo> {
    // ...
}    

你得到了基本的想法,两个接口,每个接口有两个实现。

最后,问题

现在我将为我找到棘手的部分,那就是我希望能够在我的服务获得TwitterPubInfo时自动使用TwitterPublisher。

我可以通过手动映射来实现,正如您在下面的示例中所看到的那样,但我不禁认为它会以更自动的方式存在,而不依赖于手动映射。 我使用spring,我认为在那里,它会存在一个工具来帮助我,或者其他一些实用工具,但我找不到任何东西。

@Service
public class PublishingService {

    private Map<Class, Publisher> publishers = new HashMap<Class, Publisher>();

    public PublishingService() {

        // I want to avoid manual mapping like this
        // This map would probably be injected, but 
        // it would still be manually mapped. Injection
        // would just move the problem of keeping a 
        // map up to date.
        publishers.put(FacebookPubInfo.class, new FacebookPublisher());
        publishers.put(TwitterPubInfo.class, new TwitterPublisher());
    }

    public void publish(PubInfo info, String message) {

        // I want to be able to automatically get the correct
        // implementation of Publisher

        Publisher p = publishers.get(info.getClass());
        p.publish(info, message);

    }

}

我至少可以填充publishersPublishingService与思考,对不对?

我是否需要自己做,或者在其他地方有任何帮助吗?

或者,也许你认为这种方法是错误的,并且存在一种更聪明的方法来完成我在这里需要做的事情,随意说出来并告诉我你的优越方式:p做事(真的,我很欣赏它)。

编辑1开始

在Spring编写自定义事件处理程序时,它会找到正确的实现,这就是我从这个问题中获得灵感的地方。

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-functionality-events

这是从该页面:

public class BlackListNotifier implements ApplicationListener<BlackListEvent> {

    // ...

    public void onApplicationEvent(BlackListEvent event) {
        // as you can see spring solves this, somehow, 
        // and I would like to be able to something similar
    }

}

我可以以某种方式获得相同的功能吗?

结束编辑1

你的Publisher实现是Spring bean吗?

在这种情况下,您可以使用以下所有内容:

Map<String, Publisher> pubs = context.getBeansOfType(Publisher.class);

然后,您可以询问每个Publisher是否接受您收到的PubInfo (这意味着向Publisher添加新方法,以便每个发布者可以决定它可以处理哪个PubInfo )。

该解决方案将避免手动映射,并且每个发布者将封装与其可以处理的内容相关的信息。

您还可以在每个Publisher类中使用注释,然后获取具有该注释的所有bean(并且注释可以指示Publisher可以处理的特定类)。 这是一个类似的方法,但也许你会发现注释更好

您想要做的是下面的内容......但据我所知,这不起作用。 我建议的解决方案接近于此。

// does not work...
context.getBeansOfType(Publisher<pubInfo.getClass()>.class);

Spring实际上将抽象类型的bean自动装配到映射中,键是bean名称,值是实际的bean实例:

@Service
public class PublishingService {

    @Autowired
    private Map<String, Publisher> publishers;

    public void publish(PubInfo info, String message) {
        String beanName = info.getClass().getSimpleName();
        Publisher p = publishers.get(beanName);
        p.publish(info, message);
    }
}

为此,您需要设置每个发布者的bean名称,以匹配其相应的PubInfo具体实现的简单类名。

一种方法是通过Spring的@Component注释:

@Component("FacebookPubInfo")
public class FacebookPublisher implements Publisher<FacebookPubInfo> {

    @Override
    public void publish(FacebookPubInfo pubInfo, String message) {
        // ... do something
    }
}

然后你只需要让Spring扫描这个类,并使用与TwitterPubInfo类相同的方法。

注意:如果您使用的是XML配置,则可以使用相同的方法。 而不是使用@Component并扫描您的类,只需在XML中显式设置每个发布者的bean名称。

如果你有兴趣,我已经为此创建了一个要点

感谢@eugenioy和@Federico Peralta Schaffne的答案,我可以得到我想要的结果。 我还在这个问题中找到了来自@Jonathan的有趣的commet( 在运行时获取泛型类 )。 在那个评论中提到了TypeTools,这是我需要把它放在最后一块。

我最终编写了一个自动生成映射的小组件,并且可以返回实现类。

如果您知道库中是否存在此类组件, 请告知我们 这实际上是我首先要搜索的内容(我会将我的答案标记为正确的答案,但如果您在公共仓库中的维护库中找到这样的组件,我很乐意让您的答案正确,它只需要能够做我的组件可以做的事情)。

为了获得TypeTools,我将其添加到我的pom:

    <dependency>
        <groupId>net.jodah</groupId>
        <artifactId>typetools</artifactId>
        <version>0.4.3</version>
    </dependency>

现在, PublishingService的实现看起来像这样:

@Service
public class PublishingService {

    //This bean is manually defined in application context. If spring could
    //understand how to do this from the Generic I specified below (Publisher)
    //it would be close to perfect. As I understand it, this information is
    //lost in runtime.

    @Autowired
    private ImplementationResolver<Publisher> publisherImplementationResolver;

    public void publish(PubInfo info, String message) {

        Publisher p = publisherImplementationResolver.getImplementaion(info);
        p.publish(info, message);

    }

}

bean publisherImplementationResolver由SpringContext构造

@SpringBootApplication
public class Main  {

    @Bean
    public ImplementationResolver publisherImplementationResolver() {
        //If spring could figure out what class to use, It would be even better
        //but now I don't see any way to do that, and I manually create this
        //bean
        return new ImplementationResolver<Publisher>(Publisher.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Main.class, args);
    }
}

ImplementationResolver类获取实现Publisher所有bean,并使用TypeTools映射指定的泛型(或者说应用的类型更正确)。

/**
 * Created on 2015-10-25.
 */
public class ImplementationResolver<T> implements ApplicationContextAware {

    private Class<T> toBeImplemented;


    private Map<String, T> implementations;


    private Map<Class, T> implemenationMapper;


    public ImplementationResolver(Class<T> toBeImplemented) {
        this.toBeImplemented = toBeImplemented;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        implementations = applicationContext.getBeansOfType(toBeImplemented);
    }

    @PostConstruct
    public void intializeMapper() {
        implemenationMapper = new HashMap<Class, T>();
        for (String beanName : implementations.keySet()) {
            T impl = implementations.get(beanName);

            Class<?>[] typeArgs = TypeResolver.resolveRawArguments(toBeImplemented, impl.getClass());

            implemenationMapper.put(typeArgs[0], impl);
        }
    }

    public T getImplementaion(Object whatImplementationIsDoneForMe) {
        return implemenationMapper.get(whatImplementationIsDoneForMe.getClass());
    }
}

为了测试这是否按预期工作,我有这个类:

@Component
public class ImplementationDemoResolver  implements CommandLineRunner {

    @Autowired
    PublishingService publishingService;

    @Override
    public void run(String... strings) throws Exception {
        FacebookPubInfo fb = new FacebookPubInfo();
        TwitterPubInfo tw = new TwitterPubInfo();

        PubInfo fb2 = new FacebookPubInfo();
        PubInfo tw2 = new TwitterPubInfo();

        publishingService.publish(fb, "I think I am a interesting person, doing interesting things, look at this food!");
        publishingService.publish(tw, "I am eating interesting food. Look! #foodpicture");
        publishingService.publish(fb2, "Wasted Penguinz is the sh17");
        publishingService.publish(tw2, "Join now! #wpArmy");
    }
}

当我运行程序时,我得到了这个结果( FacebookPublisherTwitterPublisher写了FACEBOOK和TWITTER):

FacebookPubInfo will provide information on how to publish on FACEBOOK. Message: I think I am a interesting person, doing interesting things, look at this food!
TwitterPubInfo will provide information on how to publish on TWITTER. Message: I am eating interesting food. Look! #foodpicture
FacebookPubInfo will provide information on how to publish on FACEBOOK. Message: Wasted Penguinz is the sh17
TwitterPubInfo will provide information on how to publish on TWITTER. Message: Join now! #wpArmy

动机

为什么选择这个而不是Federico Peralta Schaffne提供的解决方案?

此解决方案在实现类中不需要任何额外信息。 另一方面,它需要一个特殊的设置,但我认为这是值得的。 也可以在其他地方使用ImplementationResolver ,因为它是一个单独的组件。 一旦到位,它也会自动工作。

如果我相信我的同事,我可以选择Federico Peralta Schaffne提供的解决方案(并非所有人都想了解Spring和tdd),它感觉比我的解决方案更轻巧。 如果bean的名称在字符串中,则重构可能会导致一些问题(但是Intellij会找到它,也许还有其他ide:s)。

改进措施

现在,组件仅限于只有一个泛型的接口,但是如下面的代码中的签名可以涵盖更多的用例。 AdvancedPublisher<Map<T>, G<T>>这样的东西仍然会很棘手,所以它仍然不是完美的,但更好。 由于我不需要,我已经注意到了它。 它可以通过两层不同的集合来完成,所以如果你需要它,那么做起来并不复杂。

public class ImplementationResolver<T> implements ApplicationContextAware {

    // ...

    public ImplementationResolver(Class<T> ... toBeImplemented) {
        this.toBeImplemented = toBeImplemented;
    }

    // ...

    public T getImplementaion(Object ... whatImplementationIsDoneForMe) {
        // .... implementation
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM