前言:從上一節咱們知道Spring IoC主要是經過配置文件或者註解的方式並經過第三方去生成或獲取特定的對象。 Bean能夠理解爲類的代理。spring
1、Bean的信息存放在applicationConfig.xml中 spring-mvc
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <bean class=""> <property "/> //類的屬性 .... </bean> </beans>
2、bean的基本設置mvc
<bean id =" " class = " " scope=「 」 />app
id : 個人理解是一個bean有一個id,表明了這個bean,即惟一標識this
class : Java類的具體路徑,描述哪一個類,就填入那個類的路徑spa
scope :Bean的做用範圍-->(1)singleton:默認的,Spring會採用單例模式建立這個對象prototype
(2) prototype: 多例模式。(Struts2和Spring整合必定會用到)代理
3、定義了這些bean,怎麼注入到IoC容器中呢?三種方式code
一、構造器注入:依賴於構造方法實現。咱們能夠經過構造方法來建立類對象,Spring也能夠採用反射方式創造對象。(bean中有class的路徑) xml
public class User { private int id; private String username; public User(int id,String username){ this.id = id; this.username = username; } } //對應的bean
<bean id="user1" class="com.dongtian.po.User">
<constructor-arg index = "0" value = "1"/> //index = 0 表示第一個參數,value = "1" --->id = 1
<constructor-arg index = "1" value = "張三"/>
</bean>
缺點很明顯,一個參數對應一個標籤,若是有100個呢?太複雜了。
二、使用setter注入:主流方式
<bean id="user2" class="com.dongtian.po.User">
<property name="id" value="2" />
<property name="username" value="李四" /> //若是是類型,value變爲ref
</bean>
三、接口注入方式:獲取外界資源
四、不一樣的bean之間若是存在關係,就可互相引用
5、不經過XML文件,也能夠經過註解方式裝載Bean
@Component(value = "user")
public class User {
@Value("1") private int id;
@Value("張三") private String username; public User(int id,String username){ this.id = id; this.username = username; } }
@Component : 表示把這個類掃描爲Bean實例,value的值便是id
@Value :表示值的注入
有了這個類,還須要添加一個掃描器讓IoC知道去哪裏掃描對象:@ComponentScan
還有一個就是屬性注入:@Autowired,也能夠註解方法
@Autowired
private User user = null;