day 122 - bean的作用域,生命周期,工厂模式

发布时间 2023-08-04 19:35:29作者: 北海之上

bean的作用域

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围

singleton(默认)

在IOC容器中,这个bean的对象始终为单实例

在ioc容器初始化时创建对象

prototype

这个bean在IOC容器中有多个实例

在获取bean时创建对象

<!--
    scope 设置bean的作用域:
    singleton:获取该bean所对应的对象都是同一个,单例
    prototype:获取该bean所对应的对象都不是同一个,多例
-->
<bean id="student" class="com.gu.spring.pojo.Student" scope="prototype">
    <property name="sid" value="1233"></property>
    <property name="sname" value="zhangsan"></property>
</bean>

 

test

@Test
public void testScope(){
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
    Student student1 = ioc.getBean(Student.class);
    Student student2 = ioc.getBean(Student.class);
    System.out.println(student1 == student2);
​
}

 

bean的生命周期

具体过程

bean对象创建(调用无参构造器)

给bean对象设置属性

bean对象初始化之前操作(由bean的后置处理器负责)

bean对象初始化(需在配置bean时指定初始化方法)

bean对象初始化之后操作(由bean的后置处理器负责)

bean对象就绪可以使用

bean对象销毁(需在配置bean时指定销毁方法)

IOC容器关闭

FactoryBean

简介

FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。

public class UserFactoryBean implements FactoryBean<User> {
    @Override
    public User getObject() throws Exception {
        return new User();
    }
​
    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}

 

配置

<bean class="com.gu.spring.factory.UserFactoryBean"></bean>

 

test

@Test
public void testFactory(){
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
    User user = ioc.getBean(User.class);
    System.out.println(user);
}

 

over