目录
重点:
- Bean的配置
- Bean实例化的三种方式
- Bean的三种装配方式
正文:
1、Bean的配置
- 两种格式的配置文件:XML(最常用)和Properties。这种配置方式通过XML文件来注册并管理Bean之间的依赖关系。
- 在Spring中,XML配置文件的根元素是<beans>,<beans>中包含了多个<bean>子元素,每一个子元素定义了一个Bean,并描述该Bean如何被装配到Spring容器中
- 表1-- <bean>元素的常用属性及其子元素
属性或子元素名称 | 描述 |
id | Bean的唯一标识符,Spring容器对Bean的配置、管理都通过该属性来完成 |
class | 指定了Bean的具体实现类,必须是一个完整的类名,使用类的全限定名 |
scope |
用来设定Bean的作用域,默认值为singleton |
constructor-arg | <bean>的子元素,可以使用此元素传入构造参数进行实例化。该元素index属性指定构造参数的序号,type属性指定构造参数的类型,参数值可以通过ref属性或value属性直接指定,也可以通过ref或value子元素指定 |
property | <bean>的子元素,用于调用Bean实例中的setter方法完成属性赋值,从而完成依赖注入。该元素的name属性指定Bean实例中的相应属性名,ref属性或value属性用于指定参数值 |
ref | <property>、<constructor-arg>等元素的属性或子元素,可以用于指定对Bean工厂中某个实例的引用 |
value | <property>、<constructor-arg>等元素的属性或子元素,可以用于直接指定一个常量值。 |
2、Bean的实例化
在面向对象的程序中,想要使用哪个对象,就需要先实例化这个对象。在Spring中,要想使用容器中的Bean,也需要实例化Bean。
实例化Bean的三种方式:
1、构造器实例化
Spring容器通过Bean对应类中默认的无参构造方法来实例化Bean
(1)创建一个名为chapter02的Web项目,创建一个com.itheima.constructor包,在包中创建Bean1类。
package instance.constructor;
public class Bean1 {
}
(2)在包中,创建Spring的配置文件beans1.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-4.3.xsd">
<bean id="bean1" class="instance.constructor.Bean1"/>
</beans>
(3)在包中,创建测试类InstanceTest1,来测试构造器能否实例化Bean
package instance.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InstanceTest1 {
public static void main(String[] args) {
//定义配置文件路径
String xmlPath="instance/constructor/beans1.xml";
//ApplicationContext在加载配置文件时,对Bean进行实例化
ApplicationContext applicationContext=
new ClassPathXmlApplicationContext(xmlPath);
Bean1 bean=(Bean1) applicationContext.getBean("bean1");
System.out.println(bean);
}
}
ApplicationContext在加载配置文件时,Spring容器会通过id为bean1的实现类Bean1中默认的无参构造方法对Bean进行实例化。
输出结果:Bean1的地址
2、静态工厂实例化
该方式要求开发者创建一个静态工厂的方法创建Bean的实例,其Bean配置中的class属性所指定的不再是Bean实例的实现类,而是静态工厂类
(1)创建一个com.itheima.instance.static_factory包,在该包中创建一个Bean2类,不添加任何方法
package instance.static_factory;
public class Bean2 {
}
(2)创建一个MyBean2Factory类,并在类中创建一个createBean()方法来返回Bean2实例
package instance.static_factory;
public class MyBean2Factory {
//使用自己的工厂创建Bean2实例
public static Bean2 createBean(){
return new Bean2();
}
}
(3)创建配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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-4.3.xsd">
<bean id=&#