Spring autowired bean causes null pointer

后端 未结 5 1706
死守一世寂寞
死守一世寂寞 2020-12-19 04:55

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

相关标签:
5条回答
  • 2020-12-19 05:24

    Just want to add my 2 cents.

    I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.

    The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.

    0 讨论(0)
  • 2020-12-19 05:32

    Within your application context you have to do reference your 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"/>
    

    Then you've to inject it into your service :

    @Service
    public class AsyncAccountServiceImplementation implements AsyncAccountService
    {
    
     private static final String GATEWAY_IP_BLOCK = "1";
    
     @Autowired
     private OurLogger logger;
    
    }
    
    0 讨论(0)
  • 2020-12-19 05:36

    Use spring framework Unit test instead of JUnit test to inject your spring bean.

    May be that will help you.

    0 讨论(0)
  • 2020-12-19 05:42

    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.

    0 讨论(0)
  • 2020-12-19 05:43

    If you are using AspectJ you can use @Configurable:

    @Configurable
    public class OurLogger {
      ..
    }
    

    See: Using AspectJ to dependency inject domain objects with Spring

    0 讨论(0)
提交回复
热议问题