当前位置: 移动技术网 > IT编程>开发语言>Java > spring如何动态指定具体实现类

spring如何动态指定具体实现类

2019年07月22日  | 移动技术网IT编程  | 我要评论

绍兴e网房产,找不同图片,弹窗惊魂

在写接口实现时,有时会有多个实现类。这篇文章介绍在调用时通过传入字符串来指定具体的实现类。

一.接口与实现类:

// 接口
public interface serviceinterface {
  public void method();
}
 
// 具体两个实现类
@service("aservice")
public class aserviceimpl implements serviceinterface {
 
  @override
  public void method() {
    system.out.println("the impl is a");
  }
 
  @override
  public string tostring() {
    return "a";
  }
}
 
@service("bservice")
public class bserviceimpl implements serviceinterface {
 
  @override
  public void method() {
    system.out.println("the impl is b");
  }
   
  @override
  public string tostring() {
    return "b";
  }
 
}

在实现类中重写了tostring() 方法,可以自定义字符串,当调用时传入指定的字符串就能获取到相应的bean。 

二.register书写:

@service("register")
public class register implements initializingbean, applicationcontextaware {
  private map<string, serviceinterface> serviceimplmap = new hashmap<>();
  private applicationcontext applicationcontext;
 
  // 获取spring的上下文
  @override
  public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
    this.applicationcontext = applicationcontext;
  }
 
  // 获取接口实现类的所有bean,并按自己定的规则放入map中
  @override
  public void afterpropertiesset() throws exception {
    map<string, serviceinterface> beanmap = applicationcontext.getbeansoftype(serviceinterface.class);
    // 以下代码是将bean按照自己定的规则放入map中,这里我的规则是key:service.tostring();value:bean
    // 调用时,参数传入service.tostring()的具体字符串就能获取到相应的bean
    // 此处也可以不做以下的操作,直接使用beanmap,在调用时,传入bean的名称
    for (serviceinterface serviceimpl : beanmap.values()) {
      serviceimplmap.put(serviceimpl.tostring(), serviceimpl);
    }
  }
   
  public serviceinterface getserviceimpl(string name) {
    return serviceimplmap.get(name);
  }
 
}

三.测试类:

@resource
register register;
 
@test
public void testservice() {
  serviceinterface service = register.getserviceimpl("a");
  service.method();
  serviceinterface service2 = register.getserviceimpl("b");
  service2.method();
}

运行结果,如图:

备注:

在spring加载后,获取applicationcontext的方法:

实现applicationcontextaware接口的bean,在bean加载的过程中可以获取到spring的applicationcontext,这个尤其重要,applicationcontext是spring应用上下文,从applicationcontext中可以获取包括任意的bean在内的大量spring容器内容和信息

@component("informerregistry")
public final class informerregistry implements applicationcontextaware{
 
  private applicationcontext applicationcontext;
 
  @override
  public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
    this.applicationcontext = applicationcontext;
  }
}


关于spring常用bean扩展接口可参考:http://www.cnblogs.com/xrq730/p/5721366.html 

注意:

使用以下方法获取spring上下文时,会启动spring。多次写以下方法,就会启动多个spring容器

复制代码 代码如下:
applicationcontext ctx = new classpathxmlapplicationcontext("classpath:meta-inf/spring/*.xml");

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网