1. 程式人生 > >SprinvAction學習一、裝配bean:通過Java程式碼裝配bean

SprinvAction學習一、裝配bean:通過Java程式碼裝配bean

具體步驟

(1)普通的介面

(2)實現介面的類,該類為需要裝配到spring bean中

(3)配置類,由該類定義bean

示例程式碼:

介面1:(普通的介面)

package com.spring.action.javaconfig;

/**
 * 一個光碟介面
 */
public interface CompactDisc {
    void sing();//光碟的sing功能
}

介面1實現:(普通的類)

package com.spring.action.javaconfig;


/**
 * CompactDisc實現類
 */
public class SgtPeppers implements CompactDisc {
    public void sing() {
        System.out.println("sgtPeppers的sing方法");
    }
}

介面2:(普通的介面)

package com.spring.action.javaconfig;

/**
 * 媒體播放器
 */
public interface MediaPlayer {
    void play(); //一個播放方法
}

介面2實現:(在構造方法使用了@Autowired來自動注入CompactDisc引數)

package com.spring.action.javaconfig;

import org.springframework.beans.factory.annotation.Autowired;

public class CDPlayer implements MediaPlayer {
    private CompactDisc compactDisc;

    @Autowired
    public CDPlayer(CompactDisc compactDisc){
        this.compactDisc = compactDisc;
    }
    public void play() {
        System.out.println("播放器開始播放");
        compactDisc.sing();
    }
}

配置類

通過@Bean,將方法返回的例項作為Spring bean

在第二個方法中,spring會自動將bean注入到引數中。

package com.spring.action.javaconfig;


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

@Configuration
public class JavaConfig {
    //為sgtPeppers建立bean
    @Bean
    public CompactDisc compactDisc(){
        return new SgtPeppers();
    }
    //為DCPlayer建立bean
    @Bean
    public MediaPlayer mediaPlayer(CompactDisc compactDisc){
        return new CDPlayer(compactDisc);
    }
}

測試類:

package com.spring.action;

import com.spring.action.javaconfig.CompactDisc;
import com.spring.action.javaconfig.JavaConfig;
import com.spring.action.javaconfig.MediaPlayer;
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 = JavaConfig.class)
public class JavaconfigTest {
    @Autowired
    private CompactDisc compactDisc;

    @Autowired
    private MediaPlayer mediaPlayer;
    @Test
    public void play() {
        mediaPlayer.play();
    }
}

測試結果

WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
播放器開始播放
sgtPeppers的sing方法