Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @Autowired设置的某些对象始终为空,其他对象则为OK_Java_Spring_Autowired_Springsource - Fatal编程技术网

Java @Autowired设置的某些对象始终为空,其他对象则为OK

Java @Autowired设置的某些对象始终为空,其他对象则为OK,java,spring,autowired,springsource,Java,Spring,Autowired,Springsource,我一直在做我的第一个Spring项目,我遇到了一个恼人的问题 我有一个名为“UsernameService”的类,该类在dispatcher-servlet.xml中配置为bean: <bean id="usernameService" class="service.UsernameService" scope="session" > <aop:scoped-proxy /> </bean> 它工作得非常好。但是,当我尝试在另一个类中执行相同操作时,

我一直在做我的第一个Spring项目,我遇到了一个恼人的问题

我有一个名为“UsernameService”的类,该类在dispatcher-servlet.xml中配置为bean:

<bean id="usernameService" class="service.UsernameService" scope="session" >
    <aop:scoped-proxy />
</bean>
它工作得非常好。但是,当我尝试在另一个类中执行相同操作时,LogController:

<bean id="logController" class="controller.LogController" />

然后它不工作,我得到以下错误:

严重:路径为[/flexitime]的上下文中Servlet[dispatcher]的Servlet.service()引发了异常[Request processing failed;嵌套异常为java.lang.NullPointerException],其根本原因是 java.lang.NullPointerException

我已经设法(我相信)将此错误归因于这样一个事实:uns从未实际设置/创建,并且在LogController中保持为null

我在谷歌上搜索了很多,找到了很多“解决方案”,但到目前为止,它们都不起作用

谢谢!
James

自动连线
属性添加到bean中:

<bean id="usernameService" class="service.UsernameService" scope="session" autowire="byName">
    <aop:scoped-proxy />
</bean>


如何访问LogController。您是否有一个@RequestMapping方法被调用以响应webrequest,或者您正在代码中的某个地方创建新的LogController?对象可能不是由
new
创建的,以便注入工作。@gkamal LogController是从另一个控制器访问的,它本身是一个自动连接的bean:
@autowired(新行)日志控制器ls
@thorb我没有使用new关键字来初始化这个类。你能仔细检查一下代码,确保你确实使用了上面的ls变量(它没有被一些localVariable掩盖)@如果bean是由spring创建的,则Autowired字段将不会为null。很可能您正在访问的logController对象不是由spring创建的。您还可以在构造函数中添加一个log语句(如果没有,则创建一个伪语句),并验证它在spring上下文初始化期间只创建了一次。我按照您的建议创建了一个构造函数,据我所知,它只创建了一次(每次访问页面时,但确认正确)。这给了我一个错误:
属性“default autowire”不允许出现在元素“bean”中。
更新了它,很抱歉,我应该注意到我自己:(不幸的是,这仍然不起作用。
<bean id="logController" class="controller.LogController" />
<bean id="usernameService" class="service.UsernameService" scope="session" autowire="byName">
    <aop:scoped-proxy />
</bean>