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的值就有多个
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>