如果合同spring管理bean?
一、知识点
(1)如何通过xml文件配置bean?
xml文件中通过bean节点来配置bean,<bean></bean>
1 2 3 4 5 |
<!-- 配置bean --> <bean id="helloworld" class="spring.helloworld"> <property name="name" value="spring"></property> <property name="age" value="666"></property> </bean> |
- id:bean的名称。
- 在ioc容器中id必须是唯一的。
- 如果没指定,spring自动将权限限定性类名作为bean的名字。
- id可以指定多个名字,名字之间可以用逗号,分号,空格分隔。
class bean的全类名,通过反射的方式在ioc容器中创建bean,所以要求bean中必须有无参数的构造器。
(2)通过ApplicationContext实例化才能获得类,那么ApplicationContext到底是什么?
ApplicationContext是ioc容器:
- 在spring ioc容器读取bean配置创建bean实例之前,必须对他进行实例化。
- 只有在容器实例化之后,才可以从ioc容器里获取bean实例并且使用。
spring提供了两种类型的ioc容器实现:
- beanfactory ioc容器的基本实现。
- applicationcontext提供了更多的高级特性,是beanfactory的子接口。
区别是什么?
- beanfactory是spring框架的基础设施,面向spring本身。
- applicationcontext面向使用spring框架的开发者,几乎所有的应用场合都直接使用applicationcontext,而不是底层的beanfactory。
- 所以我们用applicationcontext就对了。
但是无论用哪种方式,配置文件是相同的。
(3)既然applicationcontext需要实例化,那么怎么进行实例化?
通过applicationcontext的主要实现类:
1.classpathxmlapplicationcontext:从类路径下加载配置文件
1 |
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml"); |
2.filesystemxmlapplicationcontext:从文件系统中加载配置文件
1 |
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("D:\\javaworkplace\\2.26spring\\src\\config.xml"); |
(4)接下来,如何获得bean?
方法一:
使用id来获取bean。示例如下:
1 |
helloworld helloworld = (spring.helloworld) applicationContext.getBean("helloworld"); |
这个是最常用的方法,也是最推荐使用的方法。
方法二:
不通过id,通过类型直接获取bean。示例如下:
1 |
helloworld helloworld = applicationContext.getBean(helloworld.class); |
但是这种方法有个很大的问题,假如xml文件中注册了两个相同的类:
1 2 3 4 5 6 7 8 9 10 |
<!-- 配置bean --> <bean id="helloworld" class="spring.helloworld"> <property name="name" value="spring"></property> <property name="age" value="666"></property> </bean> <bean id="helloworld2" class="spring.helloworld"> <property name="name" value="spring"></property> <property name="age" value="666"></property> </bean> |
那么返回哪一个类?
答案是会报错,找到了两个类,不知道返回哪一个。
1 |
No qualifying bean of type [spring.helloworld] is defined: expected single matching bean but found 2: helloworld,helloworld2 |
当配置中有两个或以上相同类对象的时候,spring不知道返回哪一个,就报错了。
所以建议还是用方法一吧。
二、总结
记录一下。