在寫介面實現時,有時會有多個實現類。這篇文章介紹在調用時通過傳入字元串來指定具體的實現類。 一.介面與實現類: 在實現類中重寫了toString() 方法,可以自定義字元串,當調用時傳入指定的字元串就能獲取到相應的bean。 二.register書寫: 三.測試類: 運行結果,如圖: 備註: 在sp ...
在寫介面實現時,有時會有多個實現類。這篇文章介紹在調用時通過傳入字元串來指定具體的實現類。
一.介面與實現類:
// 介面 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");