英文:
How to integrate between a Spring @Service and a non Spring object?
问题
我有一些@Service FooService
,它在请求时调用某个外部服务的API,并返回一些FooResult
。
在我的项目中,我定义了一些FooTask
。实际上,这是java.util.Function
的包装器(并且它在某些CompletableFuture
链中使用)。
理想情况下,我希望任务调用FooService.request()
。一个解决方案可能是在构造函数中注入FooService
,但我不确定这是否是一个好主意。
Spring 中应该如何做到这一点?
英文:
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
得分: 2
我认为,如果你的 FooTask
是一个函数式包装器且不保存任何状态,那么将其用作 Spring Component
(一个使用 @Component
注解标记的类)不会引起任何问题。然而,如果你的 FooTask
维护一些状态,或者你想在应用程序的某个地方创建多个实例,你可以在 Spring 框架之外创建 FooTask
的实例,并在其中自动装配 FooService
。这完全可以通过使用 AutowiredCapableBeanFactory
实现,但除非有必要,否则不要选择这种方法:
按照以下方式在 FooTask
中进行自动装配你的 FooService
:
private @Autowired
AutowireCapableBeanFactory beanFactory;
public void doSomething() {
FooTask fooTask = new FooTask();
beanFactory.autowireBean(fooTask);
// obj will now have its dependencies autowired.
}
英文:
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.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论