2012-01-14 237 views
2

我是Spring的新用戶。我正在嘗試通過註釋實現依賴注入。我 beans.xml文件是: -依賴注入註釋

<!-- Add your classes base package here -->   
<context:component-scan base-package="com.springaction.chapter01"/> 

<bean id="greeting" class="com.springaction.chapter01.GreetingImpl"> 
    <property name="greeting"> 
     <value>Naveen Jakad</value> 
    </property> 
</bean> 

豆,我要注入的是: -

package com.springaction.chapter01; 

import org.springframework.stereotype.Service; 

@Service 
public class InjectBean { 

private int id; 
private String name; 

public InjectBean() { 
    super(); 
} 
//setter getter of above instance variables.. 
} 

,並在其中我要注入上述豆的豆是: -

package com.springaction.chapter01; 

import org.springframework.beans.factory.annotation.Autowired; 

public class GreetingImpl implements Greeting { 

private String greeting; 

@Autowired 
private InjectBean myBean; 

public GreetingImpl() { 
    super(); 
} 
public GreetingImpl(String greeting) { 
    super(); 
    this.greeting = greeting; 
} 

public void setGreeting(String greeting) { 
    this.greeting = greeting; 
} 

@Override 
public void sayGreeting() { 
    System.out.println(greeting + " " + myBean); 
} 
} 

所以當我通過測試上述代碼: -

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("config.xml")); 
     Greeting greeting = (Greeting)beanFactory.getBean("greeting"); 
     greeting.sayGreeting(); 

我得到輸出「Naveen Jakad null」,意思是簡而言之,我無法實現我的目標。所以,請幫助我,讓我知道我會犯錯

回答

3

,如果你想通過@Autowired注入你不需要配置它在XML :)

您需要設置

<mvc:annotation-driven /> 
<context:component-scan base-package="com.your.base.package" /> 

春天這樣就會知道檢查註釋

0

隨着Fixus解決方案,您不需要在XML文件中,可以定義的「問候語」豆:

只需添加:

@Component // or @Service if it's also a service 
public class GreetingImpl implements Greeting { 

這樣你就不需要在xml文件中定義你的bean。

如果您使用Junit測試,只需在MyJunitClass中注入要測試的類(例如「Greeting」),並將您的上下文設置爲具有註釋驅動和組件掃描定義的類。

你可以看到doc配置你的JUnit測試: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html#integration-testing-annotations