spring若何靜態指定詳細完成類。本站提示廣大學習愛好者:(spring若何靜態指定詳細完成類)文章只能為提供參考,不一定能成為您想要的結果。以下是spring若何靜態指定詳細完成類正文
在寫接話柄現時,有時會有多個完成類。這篇文章引見在挪用時經由過程傳入字符串來指定詳細的完成類。
一.接口與完成類:
// 接口
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");
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。