1.3Helloword程序解读
戴着假发的程序员 出品
[查看视频讲解]
[1]概述
spring是一个对象工厂(容器),我可以将我们的编写的类交给spring管理,spring最终会将我们的类创建好对象存在一个map缓存中。并且为每一个对象设置一个对应的key。 我们可以通过spring工厂提供的api(getBean)获取spring为我们创建的对象。
[2]配置文件
spring的配置文件的根节点是<beans>其中的namespace和schemaLocation建议直接从文档上复制。
其中的bean标签就是配置或者叫注册我们自己的class。
id属性就是我们希望的spring缓存对象的key,class标签配置我们的类的全限定类名。一个bean标签就是给spring容器中注册了一个class。 当然如果我们没有指定id属性,spring会给一个默认的id。
注意:id必须是唯一的,绝对不能重复出现。
property是注入属性的配置,我们上面的配置中,就是通知spring帮我们注入属性accountDAO属性。name就是属性的名称(这里注意要遵循javaBean规范)。ref就是要注入的其他对象的引用(id)。
[3]spring容器创建
ApplicationContext是集合和各种功能的spring工厂之一,我们创建工厂时使用的ClassPathXmlApplicationContext。将我们的配置文件的名称传入工厂。和ClassPathXmlApplicationContext为孪生兄弟的FileSystemXmlApplicationContext也可以创建spring工厂对象。区别在于ClassPathXmlApplicationContext是读取classPath下的配置文件,而FileSystemXmlApplicationContext是加载操作系统中的其他配置文件。
ClassPathXmlApplicationContext的构造参数可以传入多个配置文件,例如:
new ClassPathXmlApplicationContext("applicationContext-dao.xml","applicationContext-service.xml");
或者
new ClassPathXmlApplicationContext(new String[]{"applicationContext-dao.xml","applicationContext-service.xml"});
当然这就要求你有多个配置文件:
每个配置文件中配置一部分bean:
applicationContext-dao.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 注册accountDAO --> 7 <bean id="accountDAO" class="com.boxuewa.dk.demo1.dao.AccountDAO"> 8 </bean> 9 </beans>
applicationContext-service.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 注册accountService --> 7 <bean id="accountService" class="com.boxuewa.dk.demo1.service.AccountService"> 8 <!-- 给accountService注入属性accountDAO --> 9 <property name="accountDAO" ref="accountDAO"/> 10 </bean> 11 </beans>
这样作的目的就是方便我们分类管理这些bean的配置。
当然你也可以使用通配符“*”的方式进行配置文件的加载:
new ClassPathXmlApplicationContext("applicationContext-*.xml");
[4]从spring容器中获取springBean的API
常用的有三种方式:
方式1:通过id获取springBean对象
AccountService bean = (AccountService) ac.getBean("accountService");
这种方式获取的springBean对象是Object类型的,取出后需要类型转换。
方式2:按照类型获取
AccountService bean = ac.getBean(AccountService.class);
这种方式取出的对象就是类型安全的,但是这种方式一定要确保整个spring容器中指定类型的bean只有一个存在,如果有多个就会报错。
方式3:同时按照类型和id获取
AccountService bean = ac.getBean("accountService",AccountService.class);