自动化扫描与装配Bean

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

  • 组件扫描:自动寻找使用了@Component 注解的类,并为其创建Bean
  • 自动装配:为使用了 @Autowired 的构造器、setter 方法、或者属性自动注入需要的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 指定扫描的包,不写参数默认为配置类所在的只扫描配置类的所在的包及子包下的组件类。

  • @ComponentScan("包名") 指定需要扫描的包
  • @ComponentScan(basePackages = {"包名","包名"}) 指定多个包
  • @ComponentScan(basePackageClasses = {"类名.class","类名.class"}) 设置类所在的包及子包
  • <context:component-scan base-package="包名" /> 在 XML 中配置

测试类

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)可避免这个异常。有多个匹配也会引发异常。

测试成功。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容