没有bean定义为Exception

时间:2015-12-28 09:16:35

标签: java spring

package com.mkyong.output; IOutputGenerator.java

public interface IOutputGenerator
{
    public void generateOutput();
}

package com.mkyong.output; OutputHelper.java

@Component
public class OutputHelper {

    @Autowired
    IOutputGenerator outputGenerator;

    public void generateOutput() {
        outputGenerator.generateOutput();
    }

    /*//DI via setter method
    public void setOutputGenerator(IOutputGenerator outputGenerator) {
        this.outputGenerator = outputGenerator;
    }*/
}

package com.mkyong.output.impl;

CsvOutputGenerator.java

@Component
public class CsvOutputGenerator implements IOutputGenerator {
    public void generateOutput() {
        System.out.println("This is Csv Output Generator");
    }
}

SpringBeans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.mkyong" />

</beans>

我在线程&#34; main&#34;中得到此异常异常org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为&#39; OutputHelper&#39;已定义

即使我已将OutputHelper标记为组件。

4 个答案:

答案 0 :(得分:2)

我已经改变了

OutputHelper output = (OutputHelper) context.getBean("OutputHelper");

OutputHelper output = (OutputHelper) context.getBean("outputHelper");

并且有效。

答案 1 :(得分:0)

您好我认为您尚未在Spring XML配置中添加以下内容

 xmlns:mvc="http://www.springframework.org/schema/mvc"

http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd

<mvc:annotation-driven/>

答案 2 :(得分:0)

您需要查看顶级异常并阅读整行。 我猜有一个例外是嵌套异常就像@Autowired xxxxxx,meas autowired fail。 我注意到了这一点:

@Autowired
IOutputGenerator outputGenerator;

@Component
public class CsvOutputGenerator implements IOutputGenerator

因此,在默认情况下,类名用于@Autowired,您可以重写为

@Autowired
IOutputGenerator csvOutputGenerator;

通知: “csvOutputGenerator”首字母是小写

答案 3 :(得分:0)

更简单的选择是在已在应用程序上下文中注册的bean中启用注释,这意味着您只需使用@Autowired而不是手动获取context.getBean()

的所有bean

只需将此行添加到SpringBeans.xml中即可 <context:annotation-config>

如果你真的想了解你在做什么,那么阅读this会有所帮助。