狂神說Java:https://space.bilibili.com/95256449
1、The Singleton Scope 單例模式(Spring默認機制)
對於同一個類,Spring容器只會創建一個實例。每次從容器中get的時候,都是同一個對象。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.kuang.pojo.User" p:name="張三" p:age="33" scope="singleton"/>
</beans>
測試類
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
}
結果
134310351
134310351
2、The Prototype Scope 原型模式
每次從容器中get的時候,都會產生一個新對象!
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.kuang.pojo.User" p:name="張三" p:age="33" scope="prototype"/>
</beans>
測試類
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
}
結果
134310351
1411892748
3、其餘的request、session、application等只能在web開發中使用到!