Spring對Bean裝配詳解


1.Spring提供了三種裝配bean的方式:

2.自動裝配bean:

3.通過Java代碼裝配bean

4.通過XML裝配bean

 


 

前言:創建對象的協作關系稱為裝配,也就是DI(依賴注入)的本質。而在Spring容器中對bean的創建時就需要對它所依賴的對象進行注入裝配。

 


 

1.Spring提供了三種裝配bean的方式

  1. 在XML中進行顯示配置;
  2. 在Java中進行顯示配置;
  3. 隱式的bean發現機制和自動裝配;

注:三種裝配方式可以結合使用,但是推薦首選第3種自動裝配,之后選用Java進行裝配,最后選用XML進行裝配。

 


 

2.自動裝配bean

自動裝配優勢:

  • 便利,自動化裝配,隱式配置代碼量少。

自動裝配限制:

  • 基本數據類型的值、字符串字面量、類字面量無法使用自動裝配來注入。
  • 裝配依賴中若是出現匹配到多個bean(出現歧義性),裝配將會失敗。

Spring實現自動裝配兩個步驟:

  • 組件掃描(component scanning):Spring會掃描@Component注解的類,並會在應用上下文中為這個類創建一個bean。
  • 自動裝配(autowiring):Spring自動滿足bean之間的依賴。

  使用到的注解:

  • @Component:表明這個類作為組件類,並告知Spring要為這個類創建bean。默認bean的id為第一個字母為小寫類名,可以用value指定bean的id。
  • @Configuration:代表這個類是配置類。
  • @ComponentScan:啟動組件掃描,默認會掃描所在包以及包下所有子包中帶有@Component注解的類,並會在Spring容器中為其創建一個bean。可以用basePackages屬性指定包。
  • @RunWith(SpringJUnit4ClassRunner.class):以便在測試開始時,自動創建Spring應用上下文。
  • @ContextConfiguration:告訴在哪加載配置。
  • @Autowired:將一個類的依賴bean裝配進來。

  代碼實現:

  播放器接口:

public interface CDPlayer {// 播放器
    void play();
}

  唱片接口:

public interface CDDisk {// 唱片
    void sing();
}

  實現播放器接口的類:

import org.springframework.stereotype.Component;

@Component
public class MediaPlayer implements CDPlayer {
    private CDDisk cd;
   @Autowired
public MediaPlayer(CDDisk cd){ this.cd = cd; } @Override public void play() { cd.sing(); } }

  實現唱片接口的類:

import org.springframework.stereotype.Component;

@Component
public class HuaHua implements CDDisk {
    private String title = "煙火里的塵埃";
    private String singer = "華晨宇";

    @Override
    public void sing() {
        System.out.println(title + "_" + singer);
    }
}

  Java配置類:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

   測試類:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// SpringJUnit4ClassRunner測試用,測試開始的時候自動創建Spring的應用上下文。
@RunWith(SpringJUnit4ClassRunner.class)
// 測試用,去指定類加載配置
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDTest {
    @Autowired
    private CDPlayer cdPlayer;

    @Test
    public void test() {
        cdPlayer.play();
    }
}

  測試結果:

 


 

3.通過Java代碼裝配bean

  優點:

  • 可以實現基本數據類型的值、字符串字面量、類字面量等注入。

  使用到的注解:

  • @Bean:默認情況下配置后bean的id和注解的方法名一樣,可以通過name屬性自定義id。
  • @ImportResourse:將指定的XML配置加載進來
  • @Import:將指定的Java配置加載進來。
  • 注:不會用到@Component與@Autowired注解。

  代碼實現:

  播放器接口與唱片接口:

public interface CDPlayer {// 播放器
    void play();
}
public interface CDDisk {// 唱片
    void sing();
}

  實現播放器的類:

public class MediaPlayer implements CDPlayer {
    private CDDisk cd;

   @Autowired
public MediaPlayer(CDDisk cd){ this.cd = cd; } @Override public void play() { cd.sing(); } }

   實現唱片的類:

import java.util.List;

public class HuaHua implements CDDisk {
    private String title;
    private String singer;
    private List<String> tracks;

    // 注入字面量
    public HuaHua(String title, String singer, List<String> tracks) {
        this.title = title;
        this.singer = singer;
        this.tracks = tracks;
    }

    @Override
    public void sing() {
        System.out.println(title + "_" + singer);
        for (String track : tracks) {
            System.out.println(track);
        }
    }
}

  總配置類(將指定的配置類組合到一起):

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
// 將指定配置類組合到一起
@Import({CDPlayerConfig.class, CDDiskConfig.class})
public class SoundSystemConfig {
}

  播放器的配置類:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CDPlayerConfig {
    private CDDisk cd;

    @Bean
    public CDPlayer cdPlayerConfig(CDDisk cd) {
        return new MediaPlayer(cd);
    }
}

  唱片配置類:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;

@Configuration
public class CDDiskConfig {
    @Bean
    public CDDisk cdDisk() {
        return new HuaHua("專輯", "華晨宇", new ArrayList<String>() {{
            add("煙火里的塵埃");
            add("國王與乞丐");
            add("齊天");
            add("我的滑板鞋2016");
        }});
    }
}

      測試類:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// SpringJUnit4ClassRunner測試用,測試開始的時候自動創建Spring的應用上下文。
@RunWith(SpringJUnit4ClassRunner.class)
// 測試用,去指定類加載配置
@ContextConfiguration(classes = SoundSystemConfig.class)
public class CDTest {
    @Autowired
    private CDPlayer cd;

    @Test
    public void test() {
        cd.play();
    }
}

  測試結果:

 


 

4.通過XML裝配bean

  優點:什么都能做。

  缺點:配置繁瑣。

  使用到的標簽:

  • <bean>:將類裝配為bean,也可以導入java配置。屬性id是為bean指定id,class是導入的類。
  • <constructor-arg>:構造器中聲明DI,屬性value是注入值,ref是注入對象引用。
  • spring的c-命名空間:起着和<constructor-arg>相似的作用。
  • <property>:設置屬性,name是方法中參數名字,ref是注入的對象。
  • Spring的p-命名空間:起着和<property>相似的作用。
  • <import>:導入其他的XML配置。屬性resource是導入XML配置的名稱。

  代碼實現(將Java配置改為了XML配置):

  播放器接口與唱片接口:

public interface CDPlayer {// 播放器
    void play();
}
public interface CDDisk {// 唱片
    void sing();
}

  實現播放器的類:

public class MediaPlayer implements CDPlayer {
    private CDDisk cd;

    public MediaPlayer(CDDisk cd){
        this.cd = cd;
    }
    @Override
    public void play() {
        cd.sing();
    }
}

  實現唱片的類:

import java.util.List;

public class HuaHua implements CDDisk {
    private String title;
    private String singer;
    private List<String> tracks;

    // 注入字面量
    public HuaHua(String title, String singer, List<String> tracks) {
        this.title = title;
        this.singer = singer;
        this.tracks = tracks;
    }

    @Override
    public void sing() {
        System.out.println(title + "_" + singer);
        for (String track : tracks) {
            System.out.println(track);
        }
    }
}

  測試類:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CDTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("soundsystem.xml");
        CDPlayer cd = context.getBean(CDPlayer.class);
        cd.play();
    }
}

  總XML配置(將播放器的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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--引入cdplayer-config.xml的配置-->
    <import resource="cdplayer-config.xml"/>
</beans>

  播放器的XML配置(將唱片的XML配置引入):

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

    <!--引入classpath:cd-config.xml的配置-->
    <import resource="classpath:cd-config.xml"/>
    <!--Spring的c命名空間寫法,cd為構造器中參數-->
    <bean id="mediaPlayer" class="com.qsh.soundsystem.MediaPlayer" c:cd-ref="huahua"/>
</beans>

  唱片的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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用<constructor-arg>元素-->
    <bean id="huahua" class="com.qsh.soundsystem.HuaHua">
        <constructor-arg value="專輯"/>
        <constructor-arg value="華晨宇"/>
        <constructor-arg>
            <list>
                <value>煙火里的塵埃</value>
                <value>國王與乞丐</value>
                <value>齊天</value>
                <value>我的滑板鞋2016</value>
            </list>
        </constructor-arg>
    </bean>
</beans>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM