---
# System prepended metadata

title: bean作用域
tags: [Spring-DI]

---

# bean作用域
###### tags: `Spring-DI`

## bean的作用域
![](https://i.imgur.com/tJ78DZ7.png)
### 單例模式(Spring默認機制)
#### 單例類只能有一個實例
![](https://i.imgur.com/G3bpPV2.png)
默認是單例模式，也可以顯式
```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的時候，都會產生一個新對象
![](https://i.imgur.com/dhmyew2.png)
```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); 
    }
```
![](https://i.imgur.com/bkj04mR.png)

### 其餘的request、session、application，這些只能在web開發中使用