Spring-bean的作用域
sjyvv 2020-01-06 19:21:36
spring
官方解释
# 单例模式Singleton
官网图解
spring默认方式为单例模式
xml配置
<bean id="user" class="com.User" scope="singleton"></bean>
<!--上下两句作用相同-->
<bean id="user" class="com.User" ></bean>
1
2
3
4
2
3
4
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user1 = applicationContext.getBean(User.class);
User user2 = applicationContext.getBean(User.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(user1 == user2);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
结果
# 原型模式Prototype
官网图解
xml配置
<bean id="user" class="com.User" scope="prototype"></bean>
1
2
2
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user1 = applicationContext.getBean(User.class);
User user2 = applicationContext.getBean(User.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(user1 == user2);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
结果
# 其他
其余4个在web开发中使用,以后再补充