包com.mkyong.output;
IOutputGenerator.java
public interface IOutputGenerator
{
public void generateOutput();
}
包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;
}*/
}
包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>
我收到此异常线程“主”中的异常org.springframework.beans.factory.NoSuchBeanDefinitionException:未定义名为“ OutputHelper”的bean
即使我已将OutputHelper标记为组件。
最佳答案
我变了
OutputHelper output = (OutputHelper) context.getBean("OutputHelper");
至
OutputHelper output = (OutputHelper) context.getBean("outputHelper");
而且有效。