依赖注释注释

时间:2012-01-14 06:44:59

标签: java spring dependency-injection annotations

我是春天的新用户。我试图通过注释实现依赖注入。我的 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> 

我要注入的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..
}

我要在bean上面注入的bean是: -

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”,简而言之,我无法实现我的目标。所以请帮帮我,让我知道我犯错的地方

2 个答案:

答案 0 :(得分:3)

如果你想通过@Autowired注入,你不需要在xml中配置它:)

您需要设置

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

春天会知道检查注释

答案 1 :(得分:0)

使用Fixus解决方案,您不需要定义“greeting”bean的xml文件:

只需添加:

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

这样您就不需要在xml文件中定义bean了。

如果您使用Junit测试,只需在MyJunitClass中注入要测试的类(例如“Greeting”),并将您的上下文设置为带有注释驱动和组件-scan定义的上下文。

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