Spring autowired bean causes null pointer

robinjohnobrien picture robinjohnobrien · Sep 23, 2014 · Viewed 41k times · Source

I have a logger class that makes use of a service. Each time a new logger is created, I expect to have access to the singleton scoped logging service.

I autowire the logging service into the logger however, a null pointer exception is returned. I have tried a few solutions:

  1. manually defining the bean in the application context,
  2. Trying to get the logger to be spring managed but that just resulted in more issues.

I am trying to get this to work in my junit tests, and I do specify the context file to make use of a different application context. However even if kept identical it does not resolve the issue.

Please find code below:

The following is an excerpt from the application context.

<context:component-scan base-package="com.platform"/>
<bean id="asyncLoggingService" class="com.platform.services.AsyncLoggingServiceImplementation" scope="prototype"/>

The following is the Logger class.

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
  }

}

I then make use of the Logger in another service in order to log whats going on. (The reason I am writing another logger is to make use of an RabbitMQ server) In the service I instantiate a new instance of the Logger and then use it accordingly.

@Service
public class AsyncAccountServiceImplementation implements AsyncAccountService
{
  private static final String GATEWAY_IP_BLOCK = "1";

  private static OurLogger logger = new      OurLogger(AsyncAccountServiceImplementation.class);

...
}

The null pointer occurs in the OurLogger when I try to call any method on the asyncLoggingService.

I then am trying to test the AsyncAccountService using JUnit. I make sure I add the different application context but it still seems to result in the null pointer exception.

If you need further information please let me know. I have seen ways to fix this but they don't seem to work so perhaps I have made a mistake somewhere or I am not understanding this all quite correctly.

Answer

Xstian picture Xstian · Sep 23, 2014

When you create an object by new, autowire\inject don't work...

See this link and this link for some workaround.

Anyway if you would inject a logger i suggest you this my answer to another topic.