在Spring IOC容器中配置Bean
- 在XML文件中通过Bean节点来配置bean
package com.metadata.action;
public class HelloWord {
private String name;
public void setName(String name) {
this.name = name;
}
public HelloWord(){
System.out.println("HelloWord对象创建");
}
public void say(){
System.out.println("Tom name:"+name);
}
}
<!--
配置Bean
class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参构造器
id:标示容器中的Bean,id唯一
-->
<bean id="helloWord" class="com.metadata.action.HelloWord">
<property name="name" value="汤姆" />
</bean>
- ID :Bean的名称。
-在IOC容器中必须唯一
-若id没有指定,Spring自动将类名作为Bean的名字
-id可以指定多个名字,名字之间可用逗号、分号、或空格分隔。
调用过程
public class SpringTest {
@Test
public void beanTest(){
//首先创建spring的IOC容器对象
ApplicationContext ioc=new ClassPathXmlApplicationContext("/spring-context.xml");
//从IOC容器中获取Bean实例
HelloWord he=(HelloWord)ioc.getBean("helloWord");
he.say();
}
}
ApplicationContext
ApplicationContext的主要实现类:
-ClassPathXmlApplicationContext:从类路径下加载配置文件。
-FileSystemXmlApplicationContext:从文件系统中加载配置文件。ConfigurableApplicationContext扩展于ApplicationContext,新增两个主要方法:refresh()和close(),让ApplicationContext具有启动,刷新和关闭上下文的能力
ApplicationContext在初始化上下文时就实例化所有的单例Bean。
WebApplicationContext是专门为WEB应用而准备的,它允许从相对于WEB根目录的路径中完成初始化工作。
//首先创建spring的IOC容器对象
//ApplicationContext代表IOC容器
//ClassPathXmlApplicationContext:是ApplicationContext接口的实现类,该类实现从类路径下来加载配置文件
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-context.xml");
依赖注入的方式
- Spring支持两种依赖注入的方式
-属性注入
-构造器注入
<!-- 通过构造器来配置bean属性 -->
<bean id="dog" class="com.metadata.action.Dog">
<constructor-arg value="哈士奇" index="0"/>
<constructor-arg value="yellow" index="1" />
<constructor-arg value="2" type="int"/>
</bean>
<!-- 使用构造器注入属性值可以指定参数的位置和和参数的类型。以区分重载构造器 -->
<bean id="dog2" class="com.metadata.action.Dog">
<constructor-arg value="柴犬" type="java.lang.String"/>
<constructor-arg value="red" type="java.lang.String" />
<constructor-arg value="10.4" type="java.lang.Double"/>
</bean>