2012-01-14 174 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