java 从另一个调用 Spring 服务类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3648635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:50:29  来源:igfitidea点击:

Calling a Spring service class from another

javaspring

提问by Joe

I have two spring bean Service classes in my project. Is it possible to call one from another? if yes, how it can be done?

我的项目中有两个 spring bean 服务类。是否可以从另一个调用一个?如果是,怎么做?

采纳答案by Pascal Thivent

I have two spring bean Service classes in my project. Is it possible to call on from another? if yes, how it can be done?

我的项目中有两个 spring bean 服务类。是否可以从另一个调用?如果是,怎么做?

The canonical approach would be to declare a dependency on the second service in the first one and to just call it.

规范的方法是在第一个服务中声明对第二个服务的依赖并直接调用它。

public class FooImpl implements Foo {
    private Bar bar; // implementation will be injected by Spring

    public FooImpl() { }
    public FooImpl(Bar bar) { this.bar = bar; }

    public void setBar(Bar bar) { this.bar = bar; }
    public Bar getBar() { return this.bar; }

    public void doFoo() {
        getBar().doBar();
    }
}

And configure Spring to wire things together (the core job of Spring) i.e. inject a Barimplementation into your Fooservice.

并配置 Spring 将事物连接在一起(Spring 的核心工作),即将Bar实现注入您的Foo服务。

回答by Steve B.

This is the point of using a dependency injection framework. The idea is that you simply declare dependencies, the framework connects them. e.g.

这是使用依赖注入框架的要点。这个想法是您只需声明依赖项,框架将它们连接起来。例如

Class A{ 
  private B b;
  public void setB(B b) { this. b=b;}
}

Class B{
  ....
}

You then wire up the framework to inject the B instance into the A. If you get an A from the framework, the B is already provided. There should be no code where you explicitly set the B instance in the A instance.

然后连接框架以将 B 实例注入 A。如果从框架中获得 A,则 B 已经提供。不应该有在 A 实例中显式设置 B 实例的代码。

Look up some references to dependency injection

查找一些对依赖注入的引用

回答by Paul Gregtheitroade

You can call anything from anything else in spring, so long as you have access to the context or bean factory where the services exist. If you don't want to traverse the contexts, you could simply pass the service references to either service in your configuration file.

您可以在 spring 中从任何其他地方调用任何内容,只要您可以访问服务所在的上下文或 bean 工厂。如果您不想遍历上下文,您可以简单地将服务引用传递给配置文件中的任一服务。