-1

I have problem while using spring boot. This example of code:

@Component
class Bat extends OtherLibrary{

    @Autowired
    public Life var;

    @PostConstruct 
    public void registerBat(){
       OtherLibraryApi api = new otherLibraryApi()
       api.register(new Bat());
    } 

    @Override
    public void onResponce(ResponceVal respVal){
         Life sum = respVal.getLife().add(var);
    }
}

Class Bat extends third party library class OtherLibrary. Thrid party library has abstract method onResponce that this library asynchronously call at some method. The problem is that when onResponce method is called it doesn't include spring context so autowired field var in method onResponce has null value.

How can I include spring context in third party library method for using autowired fields ?

foxis
  • 125
  • 6
  • How is the `Bat` class instantiated? Can you share some more code? – pleft Sep 18 '17 at 09:07
  • 1
    You are Autowiring a primitive type? How would It even work??? – Karthik R Sep 18 '17 at 09:12
  • @KarthikR, sorry I forgot about it. I changed my source code. – foxis Sep 18 '17 at 09:16
  • 1
    That wont work either! How can you `autowire` an Integer? To autowire a bean it must be managed by Spring, and Integers and other primitives are surely not! – pleft Sep 18 '17 at 09:18
  • Still its the same. Autowiring would search for eligible beans to plug to this one. Is there a bean that would be suitable for wiring for integer? No. It wont be. You need little more understanding , how beans work and Dependency injection. – Karthik R Sep 18 '17 at 09:18
  • @KarthikR, you are right. Integer is final and not eligible. Thank you for correcting me. I changed my source code another time. – foxis Sep 18 '17 at 09:23
  • The comment goes lengthy, but to continue. Do following checks and experiment on your own. 1) Check if your component scan scans right package to register beans and autowire 2) Register bean 'Life' with `@Service` or `@Component` and proceed your learning. I would recommend you to read more on to the subject. – Karthik R Sep 18 '17 at 09:26
  • @pleft, I added instantinating of my **Bat** class. – foxis Sep 18 '17 at 09:26
  • `api.register(new Bat());` this is definitely wrong (from Spring perspective)! I am not sure but how about passing `this` instead of `new Bat()`? e.g. `api.register(this);` – pleft Sep 18 '17 at 09:30
  • 1
    @pleft, thank you, it really works. :) Could you answer to my question and I marked it as answer. – foxis Sep 18 '17 at 09:35

1 Answers1

1
api.register(new Bat()); 

this is definitely wrong (from Spring perspective)! I am not sure but how about passing this instead of new Bat()? This way the Spring managed version of Bat class will be registered.

e.g.

api.register(this);
pleft
  • 7,567
  • 2
  • 21
  • 45