2015-08-19 35 views
0

我有一個簡單的Spring引導web項目,直接從模板:@Autowired春季啓動網絡項目失敗

@SpringBootApplication 
@RestController 
public class HelloWorldRestApplication { 

public static void main(String[] args) { 
    SpringApplication.run(HelloWorldRestApplication.class, args); 

    Performer p = new Performer(); 
    p.perform(); 
    } 
} 

我有一個測試,以確保自動裝配工作,而事實上它在這個測試類不(例子來自春天在行動,4):

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes=CDPlayerConfig.class) 
public class CDPlayerTest { 

@Autowired 
private CDPlayer cdp; 

@Test 
public void cdShouldNotBeNull(){ 
    assertNotNull(cdp); 
    } 
} 

和:

public class Performer { 

@Autowired 
private CDPlayer cdp; 

public void perform(){ 
    System.out.println(cdp); 
    cdp.play(); 
} 

public CDPlayer getCdp() { 
    return cdp; 
} 

public void setCdp(CDPlayer cdp) { 
    this.cdp = cdp; 
} 
} 

和:

@Component 
public class CDPlayer{ 

public void play(){ 
    System.out.println("play"); 
    } 
} 

配置:

@Configuration 
@ComponentScan 
public class CDPlayerConfig { 

} 

然而,在HelloWorldRestApplication不工作,我得到空。

添加@ContextConfiguration(classes = CDPlayerConfig.class)沒有幫助。

我錯過了什麼?

+1

靜態字段不能被裝配檢查http://stackoverflow.com/questions/10938529/why-cant -we-autowire-static-fields-in-spring解釋 –

+0

我在main方法中創建了一個POJO,然後嘗試自動裝入它的字段,但仍然失敗。因此,刪除靜態並不能解決問題 – jarosik

+0

用您的最新代碼更新文章 –

回答

0

嘗試啓用@ComponentScan你的包在你的主類和下面從ApplicationContext得到Performer類的實例:

@SpringBootApplication 
@RestController 
@ComponentScan({「package.name.1」,」package.name.2」}) 
public class HelloWorldRestApplication { 

public static void main(String[] args) { 
    ApplicationContext ctx = SpringApplication.run(HelloWorldRestApplication.class, args); 

    Performer p = ctx.getBean(Performer.class);//get the bean by type      
    p.perform(); 
    } 
} 
+0

仍然失敗,我也有與開箱即用的Spring Starter項目相同的情況 – jarosik

+1

由於'new Performer()',它失敗了,你可以嘗試更新的答案嗎? – Arpit

+0

當我將@Component添加到Performer時它可以工作,但這也可以,謝謝:) – jarosik