![](/img/trans.png)
[英]Spring @Autowired bean not initialising; Null Pointer Exception
[英]Spring autowired bean causes null pointer
我有一个使用服务的记录器类。 每次创建新记录器时,我都希望能够访问单例范围的日志记录服务。
但是,我将日志记录服务自动连接到记录器中,返回空指针异常。 我尝试了一些解决方案:
我试图让它在我的 junit 测试中工作,并且我确实指定了上下文文件以使用不同的应用程序上下文。 但是,即使保持相同,也不能解决问题。
请在下面找到代码:
以下是应用程序上下文的摘录。
<context:component-scan base-package="com.platform"/>
<bean id="asyncLoggingService" class="com.platform.services.AsyncLoggingServiceImplementation" scope="prototype"/>
下面是 Logger 类。
package com.platform.utils;
import com.platform.services.AsyncLoggingService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class OurLogger
{
private static Logger logger;
@Autowired
private AsyncLoggingervice asyncLoggingService;
public OurLogger(Class Clazz)
{
logger = LoggerFactory.getLogger(Clazz);
}
public void trace(TraceableObject object, String message)
{
//Do nothing yet
}
}
然后我在另一个服务中使用 Logger 来记录正在发生的事情。 (我编写另一个记录器的原因是为了使用 RabbitMQ 服务器)在服务中,我实例化了一个记录器的新实例,然后相应地使用它。
@Service
public class AsyncAccountServiceImplementation implements AsyncAccountService
{
private static final String GATEWAY_IP_BLOCK = "1";
private static OurLogger logger = new OurLogger(AsyncAccountServiceImplementation.class);
...
}
空指针发生在OurLogger
当我尝试呼吁任何方法asyncLoggingService
。
然后我尝试使用 JUnit 测试AsyncAccountService
。 我确保添加了不同的应用程序上下文,但它似乎仍然导致空指针异常。
如果您需要更多信息,请告诉我。 我已经看到了解决这个问题的方法,但它们似乎不起作用,所以也许我在某个地方犯了一个错误,或者我没有完全正确地理解这一切。
只想加上我的 2 美分。
当我不太习惯the life in the IoC world
时,我曾经遇到过同样的问题。 我的一个 bean 的@Autowired
字段在运行时为空。
根本原因是,我没有使用 Spring IoC 容器维护的自动创建的 bean( indeed
正确注入了其@Autowired
字段),而是newing
我自己的该 bean 实例并使用它。 当然这个@Autowired
字段是空的,因为 Spring 没有机会注入它。
如果您使用的是 AspectJ,则可以使用@Configurable
:
@Configurable
public class OurLogger {
..
}
在您的应用程序上下文中,您必须引用您的 Logger :
<context:component-scan base-package="com.platform"/>
<bean id="asyncLoggingService" class="com.platform.services.AsyncLoggingServiceImplementation" scope="prototype"/>
<bean id="ourLogger" class="com.platform.utils.OurLogger"/>
然后你必须将它注入你的服务:
@Service
public class AsyncAccountServiceImplementation implements AsyncAccountService
{
private static final String GATEWAY_IP_BLOCK = "1";
@Autowired
private OurLogger logger;
}
使用 spring 框架单元测试而不是 JUnit 测试来注入你的 spring bean。
也许那会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.