gpt4 book ai didi

java - 空指针异常 : @Autowired does not set field

转载 作者:行者123 更新时间:2023-12-01 13:48:38 24 4
gpt4 key购买 nike

我正在学习 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(

最佳答案

使用 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>

关于java - 空指针异常 : @Autowired does not set field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20144334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com