Bean的配置
Spring可以看作一个大型工厂,用于生产和管理Spring容器中的Bean。如果要使用这个工厂生产和管理Bean,需要开发者将Bean配置在Spring的配置文件中,Spring框架支持XML和 Properties两种格式的配置文件,在实际开发种常用XML格式的配置文化
XML配置文件的根元素beans,beans种包含了多个bean子元素,每个bean子元素,每个bean元素定义一个Bean,并描述Bean如何被装配到Spring容器中。
- 元素的常用属性及其子元素
Bean的配置示列如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--将指定类TestDIDaoImpl配置给Spring,让Spring配置文件-->
<bean id="myTestDIDao" class="dao.TestDIDaoImpl"/>
<!--使用构造方法注入-->
<bean id="testDiService" class="Serivce.TestDIServiceImpl">
<constructor-arg index="0" ref="myTestDIDao"/>
</bean>
</beans>
Bean的实例化
在面向对象编程中,如果想使用某个对象,需要实现实例化该对象。同样,在SPring框架中,如果想使用Spring容器中的Bean,也需要实例化Bean。Spring框架实例化Bean有3种方式,即构造方法实例化丶静态工厂实例化和实例工厂实例化(其中最常用的方法是构造方法实例化)
构造方法实例化
在Spring框架中,Spring容器可以调用Bean对应类中的无参数构造方法来实例化Bean,这种方式称为构造方法实例化。下面通过ch3应用来演示构造方法实例化的过程。
1. 创建Web应用ch3
2.创建BeanClass类
- 在ch3的src目录下创建instance包,并在该包中创建BeanClass类,代码如下:
package instance;
public class BeanClass {
public String message;
public BeanClass(){
message="构造方法实例化bean";
}
public BeanClass(String s){
message=s;
}
}
3 .创建配置文件
在ch3的src目录下创建spring的配置文件applicationContext,xml 在配置文件中定义一个id为constructorInstance的Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans ">
<!--构造方法实例化-->
<bean id="constructorInstance" class="instance.BeanClass"/>
</beans>
4.创建测试类
package test;
import instance.BeanClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestInstance {
public static void main(String[] args) {
//初始化Spring容器applicationContext,加载配置文件
ApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext");
// 测试构造方法实例化Bean
BeanClass b1=(BeanClass) appCon.getBean("constructorInstance");
System.out.println(b1+b1.message);
}
}