Spring Framework 基础 —— 第四章 Spring 相关 API
1. ApplicationContext
的继承体系
applicationContext
:接口类型,代表应用上下文,可以通过其实例获得 Spring 容器中的 Bean 对象
2. ApplicationContext
的实现类
ClassPathApplicationContext
它是从类的根路径下加载配置文件,通常情况下推荐使用这种方式。
FileSystemApplicationContext
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
AnnotationConfigApplicationContext
当使用注解配置容器对象的时候,需要使用此类来创建 Spring 容器,它用来读取注解。
3. getBean()
方法使用
getBean()
的源码如下:
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
* Singleton or Prototype design pattern. Callers may retain references to
* returned objects in the case of Singleton beans.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be obtained
*/
public Object getBean(String name) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(name);
}
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
* required type. This means that ClassCastException can't be thrown on casting
* the result correctly, as can happen with {@link #getBean(String)}.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
this.assertBeanFactoryActive();
return this.getBeanFactory().getBean(name, requiredType);
}
其中,当参的数据类型是字符串时,标识根据 Bean 的 id 从容器中获得的 Bean 实例,返回是 Object,需要强制转换。当参数的数据类型时,表示根据类型从容器中匹配的 Bean 实例,当容器中相同类型的 Bean 有多个时,用此方法会报错。
使用示例:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1 = (UserService) app.getBean("userService");
UserService userService2 = app.getBean(UserService.class);
4. Spring 的重点 API (重点)
ApplicationContext app = new ClassPathXmlApplicationContext("xml file");
app.getBean("id");
app.getBean(Class);