如何在Spring的@Service和非Spring对象之间集成?

huangapple go评论122阅读模式
英文:

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.
}

huangapple
  • 本文由 发表于 2020年8月7日 22:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63304049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定