繁体   English   中英

通过HttpInvoker基于特定接口的bean导出bean

[英]Export beans through HttpInvoker based on beans of certain interface

我们有实现接口的bean,可以说MyServicesInterface,我们可以使用以下命令在Java中自动连线为列表

@Autowired List {MyServicesInterface} myServices;

我想在应用程序上下文中使用如下sudo代码执行此操作。

<beans>

  <util:list id="servicesList" class="ArrayList" autowire-interface="com.MyServicesInterface" />
  <for-each service:services>
      <bean id="{/remote + service.getname}" class="org....HttpInvoker">
          <property name="serviceInterface" class="{#service.getInterface()}"
      </bean>
  </for-each>

<beans>

这种类型的{Interface}类型的动态for-each Bean创建了一个Exporter Bean,将是导出Bean的一种很好的模式。 我知道可以在Java中完成此操作,但是遇到一些困难,因此需要在Java中为每个bean创建一个HttpInvoker。 我怀疑是否可以在应用程序上下文中完全完成此操作,但是也许我忽略了一种方法。

任何意见或建议都很好。

使用BeanDefinitionRegistryPostProcessor为您的HttpInvokerServiceExporters创建BeanDefinition。 使用注释来标记服务并定义要导出的接口。

例如

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    for (String name : registry.getBeanDefinitionNames()) {
        try {
            BeanDefinition definition = registry.getBeanDefinition(name);
            String beanClassName = defintition.getBeanClassName();

            cls = classLoader.loadClass(beanClassName);

            if(cls.isAnnotationPresent(ExportableService.class)){
                //Get annotation and pull out serviceInterface
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                beanDef.setBeanClass(HttpInvokerServiceExporter.class);

                MutablePropertyValues values = new MutablePropertyValues();
                values.addPropertyValue("service", new RuntimeBeanReference(name));
                values.addPropertyValue("serviceInterface", "service interface from annotation>);

                beanDef.setPropertyValues(values);

                // Bean name here should be e.g. /myService so its picked up by the BeanNameUrlHandlerMapping (if you so desire)
                registry.registerBeanDefinition(<beanName>, beanDef);
            }
        }
    } catch(ClassNotFoundException e){
        // Handle exception
    }
}

我怀疑U是否可以使用xml上下文来实现,但是使用Java却很简单。 所以在Java中我会这样:

List<MyServicesInterface> mylist =  applicationContext.getBeansOfType(MyServicesInterface.class).values();

ServiceInterface si = applicationContext.getBean(ServiceInterface.class);
for(MyServicesInterface mi: mylist){
    si.callSomething(mi);
}

那就是我在Java中的样子。

暂无
暂无

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

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