我正在学习SPRING,这不是Web应用程序代码;我在字段级别使用@Autowired注释时获得NLP。
Q1)请帮忙出错?
Q2)如果我在班级有@Scope注释;我仍然需要XML bean级别吗?
@Controller
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
public class StreamingController implements psConsolePortListener.Implementation{
@Autowired
@Qualifier("scMgr")
private StreamingControllerManager streamingMgr = null;
public static void main(String[] args) {
logger.info("StreamingController testing");
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource(BEAN_FILE));
StreamingController obj = (StreamingController) factory.getBean("streamingController");
obj.streamingMgr.test();
}
}
@Service
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
@Qualifier("scMgr")
public class StreamingControllerManager {
/** Logger */
private static final Logger logger = LoggerFactory.getLogger(StreamingControllerManager.class);
private StreamingControllerManager(){
logger.info("StreamingControllerManager is called!!");
}
public void test(){
logger.info("StreamingControllerManager test!!");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<context:component-scan base-package="com.xxx.streamingController"/>
<bean id="scMgr" class="com.xxx.streamingController.StreamingControllerManager">
</bean>
<bean id="streamingController" class="com.xxx.streamingController.StreamingController">
</bean>
</beans>
输出:
Exception in thread "main" java.lang.NullPointerException
at com.pactolus.streamingController.StreamingController.main(
答案 0 :(得分:1)
使用ApplicationContext
代替BeanFactory
。
public static void main(String[] args) {
logger.info("StreamingController testing");
ApplicationContext ctx = new ClassPathXmlApplicationContext(BEAN_FILE);
StreamingController obj = (StreamingController) ctx.getBean("streamingController");
obj.streamingMgr.test();
}
同时删除<context:annotation-config />
已经填充的<context:component-scan />
并删除bean声明。您正在使用组件扫描,因此无需声明bean。
基本上离开了你。
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:component-scan base-package="com.xxx"/>
</beans>