Spring Bean
Spring bean 是spring中最重要的东西,就是包含getter和setter方法类似于pojo的东西
xml配置文件中表示为
<bean id=”myTestBean” class=”bean.MyTestBean” />
获取xml文件中MyTestBean实例
BeanFactory bf = new XmlBeanFactory (new ClassPathResource (“filename.xml”));
创建BeanFactory对象,通过新建子类实例XmlBeanFactory
根据xml文件中的声明的所有对象新建各个对象的实例
并且调用其中的实例对象(工厂模式)
MyTestBean bean=(MyTestBean) bf.getBean(”MyTestBean”)
Beanfactory在实际生产中使用比较少,大部分都是创建ApplicationContext对象
ApplicationContext context = new ClassPathXmlApplicationContext("filename.xml")
通过创建ApplicationContext生成配置文件中声明各个对象的实例
源码大致实现过程
1.读取配置文件beanFactoryTest.xml
2. 根据 beanFactoryTest.xml 中的配置找到对应的类的配置文件,并实例化,调用实例化后的实例
3. ConfigReader用于读取及验证自己配置文件 我们要用配置文件里面的东西,当然首先要做的就是读取,然后放在内存中
4. ReflectionUtil用于根据配置文件中的配置进行反射实例化,比如在上例中 beanFactoryTest.xml 出现的
<bean id =”myTestBean class=”bean.MyTestBean/>,我们就
可以根据 bean.MyTestBean 进行实例化
Spring Bean UML图
DefaultListableBeanFactory(第一个实现类非接口) UML图
XmlBeanFactory 继承自DefaultListableBeanFactory而DefaultListableBeanFactmy 是整个bean加载的核心部分,是Spring注册及加载bean的默认实现,而对于 XmlBeanFactory, DefaultListableBeanFactory不同的地方其实是在 XmlBeanFactory 中使用了自定义的 XML 读取器XmlBeanDefinitionReader ,实现了个性化的 BeanDefinitionReader 读取,DefaultListableBeanFactory 继承了 AbstractAutowireCapableBeanFactory并实现了ConfigurableListableBeanFactory以及BeanDefinitionRegistry 接口
容器的基础 XmlBeanFactory类
BeanFactory bf
= new XmlBeanFactory (new ClassPathResource (” beanFactoryTest.xml”))
XmlBeanFactory初始化过程图
Spring的配置文件读取是通过 ClassPathResource行封装的,
new ClassPathResource (”beanFactory Test.xml”)
ClassPathResource 的功能:
Java使用URL标记资源位置,通过注册不同的handler ( URLStreamHandler )
来处理不同来源的资源的读取逻辑,一般 handler类型使用不同前缀协议来识
别,然而 URL 没有默认定义相对 ClassPathServletContext 等资源的handler ,虽然可以注册自己的 URLStreamHandler,但是URL不能提供基本的方法例如是否存在等,所以Spring中使用Resource 接口封装底层资源
public interface InputStreamSource{
InputStream getinputStream() throws IOException
{
public interface Resource extends InputStreamSource{
boolean exists ();
boolean isReadable() ;
boolean isOpeη );
URL getURL() throws IOException ;
URI getURI() throws IOException ;
File getFile() throws IOException ;
long lastModified() throws IOException ;
Resource createRelative (S tring relativePath) throws IOException ;
String getFilenarne() ;
String getDescription() ;
{
在日常的开发工作中,资源文件的加载也是经常用到的,可以直接使用Spring bean提供的类获取文件资源
Resource resource=new ClassPathResource ( "beanFactoryTest.xml ”);
InputStream inputStream=resource.getinputStream ();
得到 inputStream 后,我们就可以按照以前的开发方式进行实现了,并且我们可以利用Resource 及其子类为我们提供的诸特性
XmlBeanDefinitionReader时序图
此类为加载XML文件的类
1. 获取对 XML 文件的验证模式
2. 加载 XML 文件,并得到对应的 Document
3. 根据返回的 Document 注册 Bean 信息