---
title: "Spring的IoC学习"
author: "yoyo08"
date: "2013-06-05T15:33:43Z"
tags: []
categories: ["编程语言"]
slug: "spring-ioc"
draft: false
lastmod: "2013-06-05T15:58:50Z"
id: 1882694
url: "https://yoyo08.iteye.com/blog/1882694"
---

Spring提供两种IoC容器

• BeanFactory  
• ApplicationContext

 

  如果构造器注入和setter方法注入都注入了同一个属性，并且值不一样，会怎样？

 

```
public class User {

	private String username;
	private String password;
	
	public Test(String username) {
		this.username = username;
		System.out.println(this.username);
	}

	public void init() {
		System.out.println(this.username + " ** " +this.password);
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
		System.out.println(this.username);
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
}
```

 

Bean的配置如下：

 

```
<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
	<beans>
		<bean id="userBean" class="User">
			<constructor-arg index="0">
					<value>zhangsan</value>
				</constructor-arg>
			<property name="username">
				<value>lisi</value>
			</property>
			<property name="password">
				<value>123456</value>
			</property>
		</bean>
	</beans>
```

 

输出为：

 

```
zhangsan
lisi
123456
lisi ** 123456
```

 

 Spring框架默认支持5种作用域：

 

  singleton （默认的）  
  IoC容器只会创建该Bean的唯一实例；

 

  prototype  
  IoC容器在每次请求该Bean的时候都会创建一个新的实例；

  request  
  在一次HTTP请求中，IoC容器会返回该Bean的同一个实例，对于不同的用户请求，则会返回不同的实例；

 

   session   
  在一个HTTP session 中，IoC容器会返回该Bean的同一个实例，对于不同的用户session，则会返回不同的实例；

 

  global session  
  在一个全局的HTTP session中,IoC容器会返回该Bean的同一个实例。