spring BeanFactory getbean方法是怎么搜索出对应的类的

public interface BeanFactory {
    Object getBean(String name) throws BeansException;
    
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;
    
    <T> T getBean(Class<T> requiredType) throws BeansException;
    
    ......
}

我用工具类:


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 
public class SpringContextUtil implements ApplicationContextAware {  
   private static ApplicationContext applicationContext;     //Spring应用上下文环境  
     
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
       SpringContextUtil.applicationContext = applicationContext;  
   }  

   public static ApplicationContext getApplicationContext() {  
     return applicationContext;  
   }  
    
   public static Object getBean(String name) throws BeansException {  
     return applicationContext.getBean(name);  
   } 
   
   public static <T> T getBean(Class<T> requiredType) {
       return applicationContext.getBean(requiredType);
   }
    
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {  
     return applicationContext.getBean(name, requiredType);  
   }  
    
   public static boolean containsBean(String name) {  
     return applicationContext.containsBean(name);  
   }  
    
   public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {  
     return applicationContext.isSingleton(name);  
   }  

   @SuppressWarnings("rawtypes")
public static Class getType(String name) throws NoSuchBeanDefinitionException {  
     return applicationContext.getType(name);  
   }  
    
   public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {  
     return applicationContext.getAliases(name);  
   }  
 }  

去获取spring的xml文件中的对象的时候,他们分别是怎样在xml中搜索匹配的?
getBean(Strng name) 应该是通过id或name来匹配的吧?
getBean(Class<> clzss) 呢?
另外哪里有这些用法的说明?

阅读 6.2k
2 个回答

这个就是装配Bean的机制。第二个getBean(Class<> clzss)明显是按照类型 获取,比方说,你要提取的Bean的类型是com.abc.def.test.service.LoginService
你只需要在这里给定参数是: getBean(com.abc.def.test.service.LoginService.class)
就可以得到一个LoginService的对象实例了

BeanFactory 上有 Class 到 bean_id 的 Map

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏