How to integrate between a Spring @Service and a non Spring object?

Viewed 160

I have some @Service FooService which on request, makes an API call to some external service and returns some FooResult.

In my project I defined some FooTask. This is actually a wrapper of a java.util.Function (and it being used in some CompletableFuture chain)

Ideally, I'd like the task to call FooService.request(). One solution could be injecting the FooService in the constructor but I'm not sure that's a good idea.

What is the Spring way to do that?

1 Answers

I don't think using FooTask as a Spring Component(a class which is annotated with @Component annotation) causes any problem if your FooTask is a Functional Wrapper and does not save any state, However if your FooTask maintain some state or you want to create multiple instances of that somewhere in your application you can create instances of FooTask outside Spring framework and autowire FooService in it, this is exactly possible using AutowiredCapableBeanFactory but don't go for this approach unless it is necessary:

Do it this way to autowire your FooService in FooTask:

private @Autowired
AutowireCapableBeanFactory beanFactory;
public void doSomething() {
    FooTask fooTask = new FooTask();
    beanFactory.autowireBean(fooTask);
    // obj will now have its dependencies autowired.
}
Related