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