我們?cè)谌粘i_發(fā)中,有時(shí)候會(huì)遇到需要使用接口實(shí)現(xiàn)多態(tài)的需求,那么在Spring中該如何實(shí)現(xiàn)呢?
Spring為我們提供了InitializingBean 接口,接口中的afterPropertiesSet()方法將在所有的屬性被初始化后調(diào)用,但是會(huì)在init前調(diào)用。
下面我們先來(lái)看一下該接口的定義:
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;
}
想要實(shí)現(xiàn)接口的多態(tài)注入需要進(jìn)行如下的步驟:
首先,定義一個(gè)接口類:
public interface IService {
Integer getType();
void print(String str);
}
然后寫兩個(gè)實(shí)現(xiàn)類實(shí)現(xiàn)IService接口,實(shí)現(xiàn)接口中的方法:
@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);
}
}
下面是核心的代碼,實(shí)現(xiàn)路由功能:
@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);
}
}
寫一個(gè)測(cè)試類:
@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");
}
}
那么現(xiàn)在就可以根據(jù)傳進(jìn)來(lái)的type進(jìn)行動(dòng)態(tài)的調(diào)用實(shí)現(xiàn)類,實(shí)現(xiàn)多態(tài)了。是不是很簡(jiǎn)單。
由于本人水平有限,如有錯(cuò)誤請(qǐng)大家多多包涵~