# bean作用域 ###### tags: `Spring-DI` ## bean的作用域  ### 單例模式(Spring默認機制) #### 單例類只能有一個實例  默認是單例模式,也可以顯式 ```xml= <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="戀戀" scope="singleton"/> ``` ```java= public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml"); User user = context.getBean("user2",User.class); User user2 = context.getBean("user2", User.class); System.out.println(user == user2); //true } ``` ### 原型模式 #### 原型模式就是用原型實例指定創建對象的種類,並且通過複製這些原型創建新的對象,每次從容器中get的時候,都會產生一個新對象  ```xml= <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="戀戀" scope="prototype"/> ``` ```java= public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml"); User user = context.getBean("user2",User.class); User user2 = context.getBean("user2", User.class); System.out.println(user.hashCode()); System.out.println(user2.hashCode()); System.out.println(user == user2); } ```  ### 其餘的request、session、application,這些只能在web開發中使用
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up