使用Spring InitializingBean 接口实现多态注入

我们在日常开发中,有时候会遇到需要使用接口实现多态的需求,那么在Spring中该如何实现呢?
Spring为我们提供了InitializingBean 接口,接口中的afterPropertiesSet()方法将在所有的属性被初始化后调用,但是会在init前调用。
下面我们先来看一下该接口的定义:

public interface InitializingBean {
    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     * @throws Exception in the event of misconfiguration (such
     * as failure to set an essential property) or if initialization fails.
     */
    void afterPropertiesSet() throws Exception;
}

想要实现接口的多态注入需要进行如下的步骤:
首先,定义一个接口类:

public interface IService {

    Integer getType();

    void print(String str);
}

然后写两个实现类实现IService接口,实现接口中的方法:

@Service
public class IServiceAImpl implements IService{
    @Override
    public Integer getType() {
        return new Integer(1);
    }

    @Override
    public void print(String str) {
        System.out.preintln(str);
    }
}

@Service
public class IServiceBImpl implements IService{
    @Override
    public Integer getType() {
        return new Integer(2);
    }

    @Override
    public void print(String str) {
        System.out.preintln(str);
    }
}

下面是核心的代码,实现路由功能:

@Component
public class ServiceRouter implements InitializingBean {

    private static final Map<Integer, IService> routerMap = Maps.newHashMap();

    @Autowired
    private List<IService> iServiceList;

    @Override
    public void afterPropertiesSet() throws Exception {
        for (IService service : iServiceList) {
            routerMap.put(service.getType(), service);
        }
    }

    public IService getService(Integer type) {
        return routerMap.get(type);
    }
}

写一个测试类:

@RestController
public class MyController {

    @Autowired
    private ServiceRouter router;

    @RequestMapping("/test")
    public void test(@RequestParam Integer type) {
        IService service = router.getService(type);
        service.print("hello world");
    }
}

那么现在就可以根据传进来的type进行动态的调用实现类,实现多态了。是不是很简单。

由于本人水平有限,如有错误请大家多多包涵~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,767评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,104评论 6 342
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,473评论 11 349
  • CanvasRenderingContext2D.drawImage()是 Canvas 2D API 中的方法,...
    JasonQiao阅读 3,335评论 0 1
  • 燥热的天气,总有太多不平 走在烟台的大道,纯玩团几乎没有购物团太大的坑,旅行社还问你行是不行 年少轻狂意气风发,不...
    紫拉加一阅读 3,490评论 3 1