【Spring 核心】装配Bean(一) 自动化装配

时间:2022-03-01 01:12:00

Spring从两个角度实现自动化装配:组件扫描 (Spring自动发现应用上下文中所创建的bean)自动装配(autowiring)自动满足bean之间的依赖

组件扫描:

package test.soundsystem;

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

import test.voice.Book;
/*
 * 使用basePackageClasses,spring会自动扫描这些类所在的包,
 * 建议在包中写空标记接口,用来被扫描,有利于项目重构。
 *
 * */
@Configuration
@ComponentScan(basePackageClasses={Book.class,CompactDisc.class})
public class CDPlayerConfig {
}

接口:

package test.soundsystem;

public interface CompactDisc {
    void play();
}

实现类:

package test.soundsystem;

import javax.inject.Named;
//Named 和 Component相似
@Named
public class SgtPeppers implements CompactDisc {

    private String title="Sgt. Pepper's Lonely Hearts Club Band";
    private String artist = "The Beatles";
    public void play() {
        System.out.println("Playing "+title+" by "+artist);
    }
}

测试类:

package test.soundsystem;

import javax.inject.Inject;

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;

import test.voice.Book;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Inject
    private Book book;

    @Test
    public void cdShouldNotBeNull(){
        cd.play();
        book.read();
    }
}