0

I have multi module spring-boot project where i have one sub-module (let say A) is dependency of another sub module (let say B).

Now in module B, I have to Autowire one Factory class and get instances of classes defined in module A. In the Factory class method I use (Autowired) Application context to getBeans. as shown below

@Component
public class MessageHandlerFactory {

    @Autowired
    ApplicationContext context;

    public MessageHandler provideMessageHandler(String parserName) {
        if (!this.context.containsBeanDefinition(parserName)) {
            System.out.println("No Message Parser bean found for {}"+ parserName);
            return null;
        } else {
            return (MessageHandler) this.context.getBean(parserName, MessageHandler.class);
        }
    }
}

Now when I Autowired this MessageHandlerFactory in Module B and call provideMessageHandler("PMMessageHandler") method I get NullPointerException for the ApplicationContext in the MessageHandlerFactory class.

At the same time When I bring all these FactoryClass and MessageHandler concrete classes into module B itself, I am able to get those beans returned from factory method.

Can someone explain me the reason and how can I overcome this? Is application context is different module to module in spring boot? even if we add one module as dependency of the other?

Here is a sample MessageHandler Concrete class I have, And I checked those beans are available in the module B context

@Component("PMMessageHandler")
public class PMMessageHandler implements  MessageHandler{
    @Override
    public void print() {
        System.out.println("PM Message Handler");
    }
}

Here is my class where I am calling the Factory Method,

@RequestMapping("interface")
public class DeviceInterfaceController {

    

    @Autowired
    MessageHandlerFactory messageHandlerFactory;


    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> createInterface(@RequestBody String string) {

        MessageHandler pmMH = messageHandlerFactory.provideMessageHandler("PMMessageHandler");
        pmMH.print();

        return new ResponseEntity<String>("success", HttpStatus.OK);
    }

}
mramsath
  • 462
  • 4
  • 10
  • An `@Autowired` field cannot be `null`, the application will fail to start. Which means the `MessageHandlerFactory` used isn't a spring controlled instance and thus doesn't receive any autowiring. – M. Deinum Jun 30 '21 at 08:15

0 Answers0