[英]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.