spring中自动装配bean
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:26
首先用@Component注解类:
package soundsystem;
import org.springframework.stereotype.Component;
@Component
public class TestBean{
……
}
@Component("bean id")可以为Bean命名相当于XML中的<bean name = "bean id",class="soundsystem.TestBean"></bean>
开启组件扫描spring才能自动装配bean,创建一个@ComponentScan注解的类
package soundsystem;
import org.springframework.context.annotation.ComponentScan;
//本来是import org.springframework.context.annotation.Con; 但是导入的包里没有Con只能先用*代替,反正能用 import org.springframework.context.annotation.Con;
@Configuration//不添加上包无法使用
@ComponentScan
public class TestBeanScan{ }
开启默认扫描,spring将扫描由@Component注解的类(在TestBeanScan类的soundsystem包或者其子包下),为其创建一个bean。
建一个JUnit测试类
package soundsystem;
import static org.junit.Assert.*; 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);
}
}
运行时报错

网上查,缺少两个包:hamcrest-core-1.3.rc2.jar,hamcrest-library-1.3.rc2.jar;(JUnit依赖hamcrest框架)
同时JUnit包的版本也得是JUnit4.12,我之前的是JUnit4.7,也会报错。
Build path,重新测试

如书上所说测试运行器确实出现绿色,但是控制台的输出似乎没有达到预期,不知道是什么原因,如果您知道还请在评论区告知一声,谢谢了。
自制了一个思维导图,总结学习过程

- 上一篇: Spring总结 1.装配bean
- 下一篇: spring中这些编程技巧,真的让我爱不释手
相关文章
-
Spring总结 1.装配bean
Spring总结 1.装配bean
- 互联网
- 2026年04月04日
-
spss是研究方法么
spss是研究方法么
- 互联网
- 2026年04月04日
-
spss怎么按变量将数据分成两组
spss怎么按变量将数据分成两组
- 互联网
- 2026年04月04日
-
spring中这些编程技巧,真的让我爱不释手
spring中这些编程技巧,真的让我爱不释手
- 互联网
- 2026年04月04日
-
spring整合mybatis后,mybatis一级缓存失效的原因
spring整合mybatis后,mybatis一级缓存失效的原因
- 互联网
- 2026年04月04日
-
spring源码深度解析— IOC 之 容器的基本实现
spring源码深度解析— IOC 之 容器的基本实现
- 互联网
- 2026年04月04日






