Bean的实例化就是通过Spring容器帮我们创建对象实例。
Bean的实例化有三种方式:
1、构造器实例化:使用默认的构造方法实例化
在String容器的配置文件中的配置如下:
<?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="com.qiyue.instance.constructor.Bean1" />
</beans>
2、静态工厂方式实例化:
创建一个静态工厂类,在工厂中提供一个静态方法,通过静态方法实例化Bean。
在String容器的配置文件中的配置如下:
<?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">
<!-- class属性值为静态工厂的全限定名 -->
<bean id="bean2" class="com.qiyue.instance.static_factory.MyBean2Factory"
factory-method="createBean" />
<!-- factory-method 属性值为静态工厂中的静态方法名称 -->
</beans>
3、实例工厂方式实例化:
创建实例工厂类,在工厂中提供实例Bean的方法,通过该方法实例化Bean。通过实例工厂实例化Bean的同时,实例工厂也会被实例化。
在String容器的配置文件中的配置如下:
<?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="myBean3Factory" class="com.qiyue.instance.factory.MyBean3Factory" />
<!-- 使用factory-bean属性指向配置的实例工厂,使用factory-method属性确定使用工厂中的哪个方法-->
<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean" />
</beans>