Spring中设置创建的bean实例是单实例还是多实例

简介: Spring中设置创建的bean实例是单实例还是多实例

在 Spring 里面,默认情况下,bean 是单实例对象

public class Student {
    
}
    <bean id="student" class="iocbean.byxml.example.Student">

    </bean>
public class DemoTest {
      
    @Test
    public void test1(){
      
        ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/example/bean.xml");

        Student student1 = context.getBean("student", Student.class);
        Student student2 = context.getBean("student", Student.class);

        System.out.println(student1);
        System.out.println(student2);
    }
}

结果:(可以看到两个对象地址值相同)

iocbean.byxml.example.Student@5bd03f44
iocbean.byxml.example.Student@5bd03f44

Process finished with exit code 0

在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例

默认值,singleton,表示是单实例对象prototype,表示是多实例对象
    <bean id="student" class="iocbean.byxml.example.Student" scope="prototype">

    </bean>

结果:(可以看到两个对象地址值不相同)

iocbean.byxml.example.Student@470f1802 iocbean.byxml.example.Student@63021689 Process finished with exit code 0 

singleton 和 prototype创建实例对象的区别:

设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例对象设置 scope 值是 prototype 时候,不是在加载 spring 配置文件时候创建对象,在调用 getBean 方法时候创建多实例对象
目录
相关文章
|
15天前
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
99 26
|
2月前
|
XML 安全 Java
|
2月前
|
存储 Java Spring
【Spring】获取Bean对象需要哪些注解
@Conntroller,@Service,@Repository,@Component,@Configuration,关于Bean对象的五个常用注解
|
2月前
|
存储 Java 应用服务中间件
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式
|
2月前
|
XML Java 数据格式
Spring容器Bean之XML配置方式
通过对以上内容的掌握,开发人员可以灵活地使用Spring的XML配置方式来管理应用程序的Bean,提高代码的模块化和可维护性。
73 6
|
2月前
|
XML Java 数据格式
🌱 深入Spring的心脏:Bean配置的艺术与实践 🌟
本文深入探讨了Spring框架中Bean配置的奥秘,从基本概念到XML配置文件的使用,再到静态工厂方式实例化Bean的详细步骤,通过实际代码示例帮助读者更好地理解和应用Spring的Bean配置。希望对你的Spring开发之旅有所助益。
159 3
|
2月前
|
安全 Java 开发者
Spring容器中的bean是线程安全的吗?
Spring容器中的bean默认为单例模式,多线程环境下若操作共享成员变量,易引发线程安全问题。Spring未对单例bean做线程安全处理,需开发者自行解决。通常,Spring bean(如Controller、Service、Dao)无状态变化,故多为线程安全。若涉及线程安全问题,可通过编码或设置bean作用域为prototype解决。
50 1
|
8月前
|
Java 开发者 Spring
解析Spring中Bean的生命周期
解析Spring中Bean的生命周期
73 2
|
8月前
|
XML druid Java
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
91 0
|
4月前
|
Java 开发者 Spring
Spring bean的生命周期详解!
本文详细解析Spring Bean的生命周期及其核心概念,并深入源码分析。Spring Bean是Spring框架的核心,由容器管理其生命周期。从实例化到销毁,共经历十个阶段,包括属性赋值、接口回调、初始化及销毁等。通过剖析`BeanFactory`、`ApplicationContext`等关键接口与类,帮助你深入了解Spring Bean的管理机制。希望本文能助你更好地掌握Spring Bean生命周期。
234 1