0

I am working on a class C in which I am trying to use an autowired Logger field within one of its methods. Now, I have a method foo in Class A which extends Class B. Class A does not autowire log field, but it's base class B Does. Logger is an interface with no annotation applied. log object works properly on A foo method but is null on Class C.

Class C {

  @autowired
  Logger log; 

  void bar (){

    log.info("oqoqoq"); //log is null
  }
}

interface Logger{

 //methods

}

Class B{

  @autowired
  Logger log; 

}

class A extends B{

  void foo(){

     log.info("ksksks"); //log is ok

     C obj = new C();
     obj.bar();
  }
}

What could be the reason? I do not explicitly create a Logger object as you might be suspecting.

Thanks.

dushkin
  • 1,939
  • 3
  • 37
  • 82
  • it's because you instantiate your C as C obj = new C(); this is not how Spring beans/objects are supposed to be instantiated, meaning the Autowired won't work – Stultuske Nov 28 '18 at 10:30
  • Do you mean that all the objects in spring should be components and autowired? I am a Spring newbie... – dushkin Nov 28 '18 at 10:31
  • 1
    Yes exactly , and when you are injecting interface it must have implementation for that registered as '@Component or @Bean' in your application context – Mykhailo Moskura Nov 28 '18 at 10:32
  • No. I mean that if you do C obj = new C(); -> this will behave as a normal, simple POJO, without Spring's added possibilities, like autowiring. If you want to use it as a Spring bean, then it should be an autowired/autowireable component. – Stultuske Nov 28 '18 at 10:32
  • @Stultuske if he wants to get an bean from a class there are two ways Make some class which implements ApplicationContextAware and then write a static method so he can get from context any bean from non-spring(bean managed) class , or he could mark class A and B as '@Component' – Mykhailo Moskura Nov 28 '18 at 10:35
  • @MykhailoMoskura not 'everything' in a Spring project has to be a bean/component. it all depends on how you want to use it. se "Yes exactly", isn't exactly correct. – Stultuske Nov 28 '18 at 10:37
  • Not all , i agree but almost is okey , in most cases its true) – Mykhailo Moskura Nov 28 '18 at 10:39
  • I've tried to add @Component annotaion for class C, autowire it to class A and use it instead of using the new operator. So I got the error: "Error creating bean with name 'A': Unsatisfied dependency expressed through field 'c'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'C' available: expected at least 1 bean which qualifies as autowire candidate." – dushkin Nov 28 '18 at 11:00

0 Answers0