Spring之路-聊聊Bean裝配

Spring配置主要有三種裝配機制:
1.在XML中進行顯式配置;
2.在JAVA中進行顯式配置;
3.隱式的bean發現機制和自動裝配。

一、在XML中進行顯式配置

1.創建XML配置規範

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd">

這樣,就創建了一個合法簡單的Spring XML配置
2.聲明一個簡單的bean

  <bean id="xiaoming" class="program.CoderA">
      <constructor-arg value="xiaoming" />
  </bean>

id代表bean的標識,class代表生成bean的類
3.藉助構造器注入初始bean
這裏有兩種方式進行配置:
* constructor-arg>元素
* 使用spring3.0所引入的c-命名空間

  <bean id="xiaohong" class="program.ProductManageA">
    <constructor-arg ref="xiaoming" />
  </bean>

spring遇到這個bean時,會創建一個ProductManageA的實例,並通過constructor-arg告知spring引用id爲xiaomingbean。
通過c命名空間,首先應在xml聲明其模式

xmlns:c="http://www.springframework.org/schema/c"

然後,在bean中直接聲明:

  <bean id="xiaohong" class="program.ProductManageA"
    c:_0-ref="xiaoming"/>

這裏,直接用0代表第一個構造器參數,_是因爲數字不可以作爲屬性第一個字符。也可以使用構造器名。
若需裝配集合時,我們只需要使用標籤或標籤即可,
如:
<constructor-arg>
<list>
<value>..</value>
<value>..</value>
</list>
</constructor-arg>
<!-- <set>標籤同理-->

4.設值注入
使用set方法注入是,使用標籤即可,與使用同理,也有簡化的標籤p:,與c:類同。

二、在JAVA中進行顯式配置

創建一個配置類,並設置bean返回規則

@Configuration
public class ProgramConfig {

    @Bean
    public Coder coder(){
        return new CoderA();
    }
    @Bean
    public ProductManageA productManageA(Coder coder){
        return new ProductManageA(coder);
    }
}

三、隱式的bean發現機制和自動裝配

創建一個config JAVA類

@Configuration//代表配置類
@ComponentScan//設置組件掃描
public class ProgramConfig {

}
@Component//創建可被發現的bean
public class ProductManageA implements ProductManage {


    private Coder coder;
    @Autowired//自動裝配程序員
    public ProductManageA(Coder coder){
        this.coder=coder;
    }

    @Override
    public void work() {
        System.out.println("萬惡的PM跟碼農談需求");
        coder.coding();
    }

}
//測試類
/* @RunWith(SpringJUnit4ClassRunner.class)以便在測試開始的時候自動創建Spring的應用上下文。註解 @ContextConfiguration會告訴它需要在ProgramConfig中加載配置。*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ProgramConfig.class)
public class TestProgram {

    @Autowired
    private ProductManageA pmA;
    @Test
    public final void testJavaConfig(){
        pmA.work();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章