我用 eclipse 编写了这个应用程序,它可以工作。但是当我将它部署为独立/控制台应用程序时,它找不到我注入的 StartApp bean。这是代码:
主应用:
@Component
public class StartApp {
@Autowired
private Processor proc;
public StartApp() {
System.out.println("Starting App!");
}
private void say() {
proc.say();
}
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
StartApp app = ctx.getBean(StartApp.class);
app.say();
}
}
服务:
@Service
public class Processor {
public Processor() {
System.out.println("Processor initialized!");
}
public void say() {
System.out.println("hello!");
}
}
和 applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="test.spring.desktop"/>
</beans>
我确实放了所有弹簧库和记录器,包括 slf4j 库。对于控制台命令,我把这些:
java -cp lib/*:lib/spring-3.1/*:test-spring-desktop.jar test.spring.desktop.StartApp
然后我收到这些错误消息:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [test.spring.desktop.StartApp] is defined: expected single bean but found 0:
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:271)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101)
at test.spring.desktop.StartApp.main(StartApp.java:24)