SpringBean的配置详解
- Bean的配置范围
- 默认情况下(基本的Spring环境),单纯Spring环境Bean的作用范围有两个:Singleton和prototype
- singleton:单例,默认值,Spring容器创建的时候,就会进行Bean的实例化,并储存到Bean的内部的单例池中,每次getBean时都是从单例池中获取相同的Bean实例
- prototype:原型,Spring容器初始化时不会创建Bena实例,当调用getBean时才会实例化Bean,每次getBean都会创建一个新的Bean实例。
- 当scope=singleton时
-
<bean id="userService" class="com.example.Service.Impl.UserServiceImpl" scope="singleton">
-
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); Object userService1 = context.getBean("userService"); Object userService2 = context.getBean("userService"); Object userService3 = context.getBean("userService"); System.out.println(userService1); System.out.println(userService2); System.out.println(userService3);
-
运行结果如下:
-
-
-
当scope=prototype时
-
<bean id="userService" name="aaa,bbb" class="com.example.Service.Impl.UserServiceImpl" scope="prototype">
-
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); Object userService1 = context.getBean("userService"); Object userService2 = context.getBean("userService"); Object userService3 = context.getBean("userService"); System.out.println(userService1); System.out.println(userService2); System.out.println(userService3);
-
运行结果
-
PS:如果添加了SpringWebMVC依赖,scope的值就有多个文章来源:https://www.toymoban.com/news/detail-731373.html
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
文章来源地址https://www.toymoban.com/news/detail-731373.html
到了这里,关于基于Xml方式的Bean的配置-Bean的作用范围scope配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!