自动化扫描与装配Bean

2018-07-22  本文已影响33人  tingshuo123

Sping 从两个角度来实现自动化装配Bean

一个 cd 概念

package com.project.chapter02;

public interface CompactDisc {
    
    void play();
}

实现类

package com.project.chapter02;

import org.springframework.stereotype.Component;

/*
 * spring 会自动扫描有 @Component 的类,创建 Bean
 * id 默认为类的首字母小写,如:sgtPeppers
 * 可以通过@Component("id名") 指定
 * 也可以通过 DI 提供的注解 @Named("id名")指定id
 */
@Component
public class SgtPeppers implements CompactDisc {
    
    private String title = "SgtPeppers";
    private String artist = "The Beatles";
    
    @Override
    public void play() {
        System.out.println("Playing " + title + "by" + artist);
    }

}

@Component 这个注解,表明该类是组件类,spring 会为其创建 Bean,id 默认为类的首字母小写,当然也可通过@Component("id名") 指定。

创建配置类

package com.project.chapter02;

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

@Configuration  // 表明这个类是配置类
@ComponentScan(basePackageClasses={CompactDisc.class})  // 自动为包下所有类创建 Bean
public class CDPlayerConfig {
    
}

@Configuration 表明该类是配置类,配置类不应该包含任何业务逻辑,也不因该侵入到其他业务逻辑代码中。
@ComponentScan 指定扫描的包,不写参数默认为配置类所在的只扫描配置类的所在的包及子包下的组件类。

测试类

package com.project.chapter02;

import static org.junit.Assert.assertNotNull;

import org.junit.Rule;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
    
    @Autowired  // 自动注入
    private CompactDisc cd;
    
    @Test
    public void cdShouldNotBeNull() {
        assertNotNull(cd);  // 断言 cd 不为 null
    }
}

@RunWith(SpringJUnit4ClassRunner.class) 自动创建spring的上下文
@ContextConfiguration(classes=CDPlayerConfig.class) 指定配置类
@Autowired spring 会自动寻找需要的Bean,然后将其注入,如果没有匹配的Bean spring 会抛出一个异常,通过设置@Autowired(required=false)可避免这个异常。有多个匹配也会引发异常。

测试成功。。。

上一篇 下一篇

猜你喜欢

热点阅读