先看两种方式在IOC容器取得bean
1 beanFactory 实现
ClassPathResource res=new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory=new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
Dog d1=(Dog)factory.getBean("dog");
日志
[main] INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [beans.xml]
2通过applictaionContext 方式实现
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
Dog d=(Dog)ac.getBean("dog");
日志
2013-03-16 21:21:36,266 [main] INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [beans.xml]
2013-03-16 21:21:36,919 [main] INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiatin
g singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@899e53: defining beans
看看日志,applicationContext似乎就是按照第一个方式得到bean的咯,
现在看下这俩到底有些什么东东咯?
BeanFactory 类是ioc容器最基本的形式,并且提供了IOC容器所应该遵守的最基本的服务契约,勾画了IOC最基本的轮廓。
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
T getBean(String name, Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException;
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
APPlicationContext类,看实现,它继承了BeanFactorys,所以具有BeanFactory的功能,这样ApplicationContext的功能就会比BeanFactory丰富咯。它可以支持不同的信息源,由于它扩展了MessageSource,可以从不同的地方访问资源,由于实现了ResourceLoader,
public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
String getId();
String getDisplayName();
ApplicationContext getParent();
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}