spring中自动装配bean


首先用@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,重新测试

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

自制了一个思维导图,总结学习过程

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM