Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a service class in a non component class

I have my service class which does a post call. I would like to instantiate that bean/ autowire it to create a object in another class which is not a component or configuration class.

@Service
public class SavePayload {

  // Rest Post Call implementation 

}



    public class PayloadRecord
            implements Record {

        private String payload;

        PayloadProcessor payloadProcessor = new PayloadProcessor();

        public PayloadRecord(String payload) {
            this.payload = payload;
        }

        @SneakyThrows
        @Override
        public boolean isValid() throws ValidationException {
            payloadProcessor.savePayload(payload);
            return true;
        }

        @Override
        public byte[] getBytes(Charset charset) {
            return payload.getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public String getID() {
            return payload;
        }


        @Override
        public String toString() {
            return payload;
        }

        private static class PayloadProcessor {

            @Autowired
            private SavePayload savePayload;

        }

    }

I'm using a template which will do the record processing. As soon as I got message received I'm assigning it to Payload in Payload Record which is non component class. I would like to initialize the SavePayload service. Save payload service is returning null.

like image 294
TechGeek Avatar asked Sep 16 '25 09:09

TechGeek


1 Answers

Create an application context aware class so you can get the current context, something like:

@Component
public class ContextAwareClass implements ApplicationContextAware {

    private static ApplicationContext ctx;

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;
    }
}

Then, just get the context and get the bean like:

public class YourRegularNoSpringComponentClass {

    public void doSomething() {
        System.out.println(ContextAwareClass
                .getApplicationContext()
                .getBean("savePayload")
        );
    }
}

Above will print the bean if it exist in your context. In your case you would simple use it rather than print it.

Hope this helps!

like image 112
arturo.bhn Avatar answered Sep 19 '25 03:09

arturo.bhn