我用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>
我确实把所有Spring库和logger包括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)
答案 0 :(得分:0)
尝试将applicationCntext.xml放入此配置:
<context:annotation-config />