美文网首页
使用Spring InitializingBean 接口实现多态

使用Spring InitializingBean 接口实现多态

作者: 蔓越莓饼干 | 来源:发表于2017-07-07 13:58 被阅读0次

我们在日常开发中,有时候会遇到需要使用接口实现多态的需求,那么在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 InitializingBean 接口实现多态

      本文链接:https://www.haomeiwen.com/subject/gcilhxtx.html