以前,一直不清楚spring容器的概念,现在终于理解了。
spring作为容器,其实最重要的就是配置文件xml。在里面创建好各种各样的bean,有属性注入的(注入字符串、list、map、set等集合)、函数注入、对象注入(将一个bean通过ref引用注入到)等,这一步只是创建好了bean,但是还没有放到容器中,要将其放到容器中才可以使用。容器有两种,分别是BeanFactory、上下文ApplicationContext。放入容器,就是将配置文件xml加载进来,具体加载方式如下表,这个时候并没有创建bean实例,在getBean时才真正创建了bean实例。
BeanFactory方式
主要是用XmlBeanFactory
加载方法有多种,分别是
org.springframework.core.io.ByteArrayResource | 字节给定的内容 |
org.springframework.core.io.ClassPathResource | 从classpath提取资源 |
org.springframework.core.io.DescriptiveResource | 资源描述符 |
org.springframework.core.io.FileSystemResource | 从文件系统提取资源 |
org.springframework.core.io.InputStreamResource | 从输入流提取资源 |
org.springframework.web.context.support.ServletContextResource | 从servlet上下文中取资源 |
org.springframework.core.io.UrlResource | 从给定的url中取资源 |
具体使用如下(以文件系统提取举例子):
BeanFactory factory=new XmlBeanFactory(new FileSystemResource("c:/beans.xml"));
ApplicationContext方式
加载方法主要有三种,如下
org.springframework.context.support.ClassPathXmlApplicationContext | 从类路径中的xml文件载入bean资源 |
org.springframework.context.support.FileSystemXmlApplicationContext | 从文件系统中的xml文件载入bean资源 |
org.springframework.web.context.WebApplicationContext | 从web系统中的xml中载入Bean资源 |
ApplicationContext ctx = new ClassPathXmlApplicationContext( "com/springinaction/springidol/spring-idol.xml");
下面通过几个例子来加强下理解
1.配置bean(各种注入如下)
<bean id="baseSaxophonist" class="com.springinaction.springidol.Instrumentalist" abstract="true"> <property name="song" value="Jingle Bells" /> //注入字符串 <property name="instrument" ref="saxophone" /> //注入对象 </bean>
<bean id="hank" class="com.springinaction.springidol.OneManBand"> <bean id="duke" |
2.将bean放到容器中
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"com/springinaction/springidol/spring-idol.xml");
3.实例化bean
TalentCompetition competition = (TalentCompetition) ctx.getBean("springIdol");
通过反射机制,可以使用bean对应class里面的方法。