如何从注解中实现接口

我在我的项目中使用 guice 进行依赖注入。我有几个具有默认绑定的接口。

我想提供一种工具,用户可以在其中实现接口,并且该自定义实现将绑定到默认实现上。如果不存在自定义实现,则应发生默认绑定。

如何才能做到这一点?我想到了一种方法,用户可以使用注释对实现的类进行注释,我可以从中获取接口并将该类绑定到该接口。这可能吗?


翻过高山走不出你
浏览 238回答 3
3回答

杨__羊羊

此外,您可以使用 SPI&nbsp;&nbsp;&nbsp;&nbsp;ServiceLoader<SayHello>&nbsp;services&nbsp;=&nbsp;ServiceLoader.load(SayHello.class);如果services为空,则可以新建默认实例。

喵喔喔

当你使用spring框架时,你可以使用声明一个bean&nbsp;@ConditionalOnMissingBean,如果没有,你可以尝试这样实现(检查对象是否声明了bean)

动漫人物

可能最好是有一个 BeanFactory,然后用户应该为给定的接口提供他的实现:class BeanFactory {&nbsp; &nbsp; private static final Map<Class<?>, ?> beans = new HashMap<>();&nbsp; &nbsp; public static <T> void register(Class<T> type, T impl){&nbsp; &nbsp; &nbsp; &nbsp; beans.put(type, impl);&nbsp; &nbsp; }}这样你就可以让你的 bean 最初在上面的工厂中声明,然后它们可能会被用户覆盖。class MyImpl implements MyService{&nbsp; &nbsp; static{&nbsp; &nbsp; &nbsp; &nbsp; BeanFactory.register(MyService.class, new MyImpl());&nbsp; &nbsp; }&nbsp; &nbsp; // Rest of code}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java