【问题标题】:dependency Injection by annotation通过注解进行依赖注入
【发布时间】:2012-01-14 06:44:59
【问题描述】:

我是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> 

我要注入的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 是:-

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”,简而言之,这意味着我无法实现我的目标。所以请帮助我,让我知道我在哪里犯了错误

【问题讨论】:

    标签: java spring dependency-injection annotations


    【解决方案1】:

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

    你需要设置

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

    这样 spring 就会知道检查注释

    【讨论】:

      【解决方案2】:

      使用 Fixus 解决方案,您不需要在其中定义“问候”bean 的 xml 文件:

      只需添加:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-26
        • 2019-10-18
        • 2020-10-24
        • 1970-01-01
        • 2016-12-28
        • 2019-03-09
        • 2021-03-12
        相关资源
        最近更新 更多