Spring中ApplicationContext和beanfactory區別
1.依賴注入
- 設值注入
//Person.java
public class Person{
private Address address;
//set方法
...
}
//Address.java
public class Address{
...
}
//配置文件
<bean id="address" class="***.Address"/>
<bean id="person" class="***.Person">
<property name="address" ref="address"/>
</bean>
- 構造注入
//Person.java
public class Person{
private Address address;
//構造方法
public Person(Address address){
this.address = address;
}
}
//Address.java
public class Address{
...
}
//配置文件
<bean id="address" class="***.Address"/>
<bean id="person" class="***.Person">
<constructor-arg ref="address"/>
</bean>
2. 注入集合值
Java類
public class Test{
//一系列集合
private List<String> schools;
private Map scores;
private Map<String, Axe> phaseAxes;
private Properties health;
private Set axes;
private String[] books;
...
}
配置文件
<bean id="test" class="***.Test">
<!-- List<String> -->
<property name="schools">
<list>
<value>小學</value>
<value>初中</value>
<value>高中</value>
</list>
</property>
<!-- Map -->
<property name="scores">
<map>
<entry key="語文" value="22"/>
<entry key="數學" value="33"/>
<entry key="英語" value="44"/>
</map>
</property>
<!-- Map<String,Axe> -->
<property name="phaseAxes">
<map>
<entry key="原始社會" value-ref="stoneAxe"/>
<entry key="農業社會" value-ref="stellAxe"/>
</map>
</property>
<!-- Properties -->
<property name="health">
<props>
<prop key="血壓">正常</prop>
<prop key="身高">1.82</prop>
</props>
</property>
<!-- Set -->
<property name="axes">
<set>
<!-- 每個value,ref,bean..都配置一個set集合 -->
<value>普通的字符</value>
<bean class="***.SteelAxe"/>
<ref bean="stoneAxe"/>
<!-- 爲set集合配置一個List集合作爲元素 -->
<list>
<value>20</value>
<!-- 再次爲List集合配置一個set集合作爲元素 -->
<set>
<value type="int">30</value>
</set>
<list>
</set>
</property>
<!-- String[] -->
<property name="books">
<value>哈哈</value>
<value>嘻嘻</value>
<value>嘿嘿</value>
</property>
</bean>
3. Spring3.0註解配置
@Configuration
public class AppConfig{
//相當於定義一個personName的變量,值爲“孫悟空”
@Value("孫悟空") String personName;
//配置一個bean:chinese
@Bean(name="chinese")
public Person person(){
Chinese p = new Chinese();
p.setAxe(stoneAxe());
p.setName(personName);
return p;
}
//配置bean:stoneAxe
@Bean(name="stoneAxe")
public Axe stoneAxe(){
return new StoneAxe();
}
}
- @Configuration:用於修飾一個Java配置類
- @Bean:用於修飾一個方法,將方法返回值定義成容器的一個Bean
- @Value:修飾一個Field。配置一個變量。
4. Spring容器中,Bean實例的生命週期
開始–>創建實例–>注入依賴關係–>調用afterPropertiesSet(實現InitializingBean接口)–>調用init-method方法–> …. –>調用destroy(實現DisposableBean接口)–>調用destroy_method方法–>結束
5.協調作用域不同步的Bean(lookup)
步驟:
- 將調用者Bean的實現類定義爲抽象類,並定義一個抽象方法來獲取被依賴的Bean
- 在